首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >this.constructor.apply对this.parent.apply

this.constructor.apply对this.parent.apply
EN

Stack Overflow用户
提问于 2015-03-11 11:44:36
回答 1查看 176关注 0票数 2

传统上,对象继承如下所示:

代码语言:javascript
运行
复制
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;

但在我看来,这也是可行的,而且看起来更好:

代码语言:javascript
运行
复制
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;

所以,

使用第一种方法的真正原因是什么?

如果我使用第二种方法,我会遇到什么问题?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-03-11 11:52:15

使用第一种方法的真正原因是什么?

事实上,这两种方法都不能正常工作。如果有另一个继承自Child的类,this.parentthis.constructor将不会指向预期的函数--您要么跳过一个级别,要么进入无限递归。

如果我使用第二种方法,我会遇到什么问题?

(new Child).constructor将是Parent,这有点出乎意料。见Is there a good use case for the constructor property in Javascript?。当然,上面的问题仍然存在,不管您是使用parent还是constructor作为属性名来引用父类。

对于正确的“超级”调用,显式引用父构造函数:

代码语言:javascript
运行
复制
function Child() {
   Parent.apply(this,arguments);
   console.log('child constructor');
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/28985771

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档