【问题标题】:Is "Subclass.prototype.constructor = Subclass" needed when inheriting objects in Javascript?在Javascript中继承对象时是否需要“Subclass.prototype.constructor = Subclass”?
【发布时间】:2011-12-07 10:55:00
【问题描述】:

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

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),这对我来说似乎是错误的。

如果我添加:

Student.prototype.constructor = Student;

然后Student.prototype.constructor 返回Student(name, id),正如预期的那样。

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

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

【问题讨论】:

标签: javascript inheritance constructor prototypal-inheritance


【解决方案1】:

阅读这个 SO 问题Prototype inheritance. obj->C->B->A, but obj.constructor is A. Why?

它应该会给你一个答案。


【讨论】:

    猜你喜欢
    • 2015-07-10
    • 2016-08-01
    • 2020-10-09
    • 1970-01-01
    • 2012-05-03
    • 2019-01-30
    • 1970-01-01
    • 2013-07-20
    相关资源
    最近更新 更多