Reputation: 171321
Consider the following example where Student
inherits from 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
As you can see, instantiating a Student
object and calling its methods works just fine, but Student.prototype.constructor
returns Person(name)
, which seems wrong to me.
If I add:
Student.prototype.constructor = Student;
then Student.prototype.constructor
returns Student(name, id)
, as expected.
Should I always add Student.prototype.constructor = Student
?
Could you give an example when it is required ?
Upvotes: 3
Views: 1508
Reputation: 1354
Read this SO question Prototype inheritance. obj->C->B->A, but obj.constructor is A. Why?.
It should give your an answer.
Upvotes: 1