问题
如何检索子级(任何继承深度级别)的构造函数名称?
解释
让我们上课Cat
扩展了 Model
类(class)。和类Kitten
扩展了 Cat
类。
我想要的是打印到控制台的(例如)字符串"Kitten"
当一个人创建 Kitten
类实例和字符串 "Cat"
当一个人创建 Cat
类实例。
诀窍是输出构造函数名称的代码应位于基类(对于所示示例为 Model
)。
注意:我擅长 Ruby,与 Javascript 相比(在我自己的范围内)。所以 “伪代码” 应该是 Ruby-ish 代码 =)
# pseudo-Ruby-code
class Model
def initialize
console.log(self.constructor.toString())
end
end
class Cat << Model
# something goes here
end
class Kitten << Cat
# and here too
end
# shows "Model"
Model.new
# shows "Kitten"
Kitten.new
# shows "Cat"
Cat.new
最佳答案
这就是我使用 Coffee-Script 的方式。
class Model
constructor: (animal = "Model") ->
console.log animal;
class Cat extends Model
constructor: (animal = "Cat") ->
super animal
class Kitten extends Cat
constructor: (animal = "Kitten") ->
super animal
new Kitten()
// => Kitten
这是编译后的 JavaScript:
var Cat, Kitten, Model,
__hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
Model = (function() {
function Model(animal) {
if (animal == null) {
animal = "Model";
}
console.log(animal);
}
return Model;
})();
Cat = (function(_super) {
__extends(Cat, _super);
function Cat(animal) {
if (animal == null) {
animal = "Cat";
}
Cat.__super__.constructor.call(this, animal);
}
return Cat;
})(Model);
Kitten = (function(_super) {
__extends(Kitten, _super);
function Kitten(animal) {
if (animal == null) {
animal = "Kitten";
}
Kitten.__super__.constructor.call(this, animal);
}
return Kitten;
})(Cat);
new Kitten();
可以自己试试here
关于Javascript child 的构造函数名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14484131/