考虑下面的示例,其中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吗?
你能在需要的时候举个例子吗?
发布于 2011-11-17 22:27:30
请阅读这篇文章,向Prototype inheritance. obj->C->B->A, but obj.constructor is A. Why?提问。
它应该会给你一个答案。
https://stackoverflow.com/questions/7762920
复制相似问题