在Javascript中继承对象时需要“Subclass.prototype.constructor = Subclass”吗?

时间:2011-10-14 04:07:06

标签: javascript inheritance constructor prototypal-inheritance

请考虑以下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吗?

你能在需要时给出一个例子吗?

1 个答案:

答案 0 :(得分:1)

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

它应该给你答案。