请考虑以下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
吗?
你能在需要时给出一个例子吗?
答案 0 :(得分:1)