Javascript子对象';构造函数名称 问题:
如何检索(任何继承深度级别的)子构造函数名称 解释 让我们使用扩展Javascript子对象';构造函数名称 问题:,javascript,oop,inheritance,Javascript,Oop,Inheritance,如何检索(任何继承深度级别的)子构造函数名称 解释 让我们使用扩展模型的类Cat。以及扩展猫类的猫类 当创建Kitten类实例时,我想要的是打印到控制台(例如)字符串“Kitten”,当创建Cat类实例时,我想要的是打印到控制台的字符串“Cat” 诀窍在于输出构造函数名称的代码应该位于基类(Model,对于所示的示例) 注意:与Javascript相比,我擅长Ruby。所以“伪代码”应该是Ruby-ish代码=) #伪Ruby代码 类模型 def初始化 console.log(self.cons
模型的类Cat
。以及扩展猫类的猫类
当创建Kitten
类实例时,我想要的是打印到控制台(例如)字符串“Kitten”
,当创建Cat
类实例时,我想要的是打印到控制台的字符串“Cat”
诀窍在于输出构造函数名称的代码应该位于基类(Model
,对于所示的示例)
注意:与Javascript相比,我擅长Ruby。所以“伪代码”应该是Ruby-ish代码=)
#伪Ruby代码
类模型
def初始化
console.log(self.constructor.toString())
结束
结束
class Cat这是我使用Coffee脚本的方式
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();
你可以自己试试当你在JavaScript中尝试这样的类继承时,上帝会执行删除新的Kitten()
——我自己也忍不住。把一个参数传递给超级
构造函数怎么样?@Jack让我们假设类确实有一些bodies@Amberlamps你能举些例子吗?这可能,可以使用构造函数模式和typeof
,但我不推荐使用它。您知道在不修改子类构造函数的情况下执行此操作的方法吗?仅父类=)例如,不向父类的构造函数传递任何附加参数。@shybovycha:如果创建从其他类继承的类的实例,则不会自动触发父类构造函数。我在OOP方面不是很有经验,但是在创建一个自动执行其父构造函数的子实例时使用的是什么语言呢?
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();