传统上,对象继承如下所示:
function Parent() {
console.log('parent constructor');
}
Parent.prototype.method = function() {
console.log('parent method');
}
function Child() {
this.parent.apply(this,arguments);
console.log('child constructor');
}
Child.prototype = Object.create(Parent.prototype);
Child.prototype.constructor = Child;
Child.prototype.parent = Parent;
但在我看来,这也是可行的,而且看起来更好:
function Parent() {
console.log('parent constructor');
}
Parent.prototype.method = function() {
console.log('parent method');
}
function Child() {
this.constructor.apply(this,arguments);
console.log('child constructor');
}
Child.prototype = Object.create(Parent.prototype);
// without next lines, constructor will be Parent
// Child.prototype.constructor = Child;
// Child.prototype.parent = Parent;
所以,
使用第一种方法的真正原因是什么?
如果我使用第二种方法,我会遇到什么问题?
发布于 2015-03-11 11:52:15
使用第一种方法的真正原因是什么?
事实上,这两种方法都不能正常工作。如果有另一个继承自Child
的类,this.parent
和this.constructor
将不会指向预期的函数--您要么跳过一个级别,要么进入无限递归。
如果我使用第二种方法,我会遇到什么问题?
(new Child).constructor
将是Parent
,这有点出乎意料。见Is there a good use case for the constructor property in Javascript?。当然,上面的问题仍然存在,不管您是使用parent
还是constructor
作为属性名来引用父类。
对于正确的“超级”调用,显式引用父构造函数:
function Child() {
Parent.apply(this,arguments);
console.log('child constructor');
}
https://stackoverflow.com/questions/28985771
复制相似问题