3

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

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

4

1 回答 1

1

阅读这个 SO 问题原型继承。obj->C->B->A,但是obj.constructor是A。为什么?.

它应该会给你一个答案。


于 2011-11-17T14:27:30.247 回答