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
ますか?
必要な場合の例を教えてください。