首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在Javascript中继承对象时是否需要"Subclass.prototype.constructor = Subclass“?

在Javascript中继承对象时是否需要"Subclass.prototype.constructor = Subclass“?
EN

Stack Overflow用户
提问于 2011-10-14 12:07:06
回答 1查看 1.5K关注 0票数 3

考虑下面的示例,其中Student继承自Person

代码语言:javascript
复制
function Person(name) {
    this.name = name;
}
Person.prototype.say = function() {
    console.log("I'm " + this.name);
};

function Student(name, id) {
    Person.call(this, name);
    this.id = id;
}
Student.prototype = new Person();
// Student.prototype.constructor = Student;    // Is this line really needed?
Student.prototype.say = function() {
    console.log(this.name + "'s id is " + this.id);
};

console.log(Student.prototype.constructor);   // => Person(name)

var s = new Student("Misha", 32);
s.say();                                      // => Misha's id is 32

正如您所看到的,实例化一个Student对象并调用它的方法很好,但是Student.prototype.constructor返回Person(name),这在我看来是错误的。

如果我添加:

代码语言:javascript
复制
Student.prototype.constructor = Student;

然后,不出所料,Student.prototype.constructor返回Student(name, id)

我应该总是添加Student.prototype.constructor = Student吗?

你能在需要的时候举个例子吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2011-11-17 22:27:30

请阅读这篇文章,向Prototype inheritance. obj->C->B->A, but obj.constructor is A. Why?提问。

它应该会给你一个答案。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/7762920

复制
相关文章

相似问题

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