3
看看下面的例子,其中來自Person
Student
繼承:在繼承Javascript中的對象時需要「Subclass.prototype.constructor = Subclass」嗎?
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構造屬性的意義是什麼?(http://stackoverflow.com/questions/4012998/what-it-the-significance-of-the-javascript-constructor-屬性) – Domenic