【发布时间】:2014-11-20 21:54:43
【问题描述】:
我用其他语言编写了一些东西,你继承了一个类,并且在创建子类的对象时调用超类构造函数。但是,在我发现的所有从 javascript 继承的模式中,超级构造函数实际上是在建立继承时运行的。
例子:
var thingy = function(){ this.constructionTime = new Date() };
var thing2 = function(){ this.type="thing2" };
thing2.prototype = new thingy();//thingy constructor actually runs here
var t2 = new thing2();//does NOT call thingy constructor
setTimeout(function(){
var t3 = new thing2();
t3.constructionTime == t2.constructionTime; // TRUE
},100);
然后我发现了一些不太常见的例子,他们做了这样的事情:
var athing = function(){
this.constructionDate = new Date();
}
athing.prototype.showDate = function(){ console.log(this.constructionDate) };
var something = function(){
athing.apply(this);
this.note = "I'm something";
}
var x = new something();
然后调用 x = new something() 会运行构造函数,但不会继承方法。所以我加了
something.prototype = athing.prototype;
它不给 x 方法,而是新对象
y = new something();
y.showDate();//shows the date generated during its construction
确实有。
所以这是我可能过于宽泛的问题:我错过了什么吗?除了希望你的超级构造函数只运行一次之外,是否有理由不使用这种模式?
【问题讨论】:
-
并不总是需要调用超级构造函数。
-
好吧,我见过原型没有初始化任何变量等的代码,只是提供了一些方法,所以在这种情况下运行超级构造函数是不必要的,对吧?但是以我的代码为例,构造函数不仅做了一些事情,而且不仅仅是将变量初始化为固定值......
-
通过将 Child 原型设置为 Parent 原型进行继承并不好。狗是动物,但动物并不总是狗。如给定的答案;最好使用 Object.create。以下答案可能对您有所帮助:stackoverflow.com/questions/16063394/…