In the section about inheritance in the MDN article Introduction to Object Oriented Javascript, I noticed they set the prototype.constructor:
// correct the
It is not necessary. It is just one of the many things traditional, OOP champions do to try to turn JavaScript's prototypical inheritance into classical inheritance. The only thing that the following
Student.prototype.constructor = Student;
does, is that you now have a reference of the current "constructor".
In Wayne's answer, that has been marked as correct, you could the exact same thing that the following code does
Person.prototype.copy = function() {
// return new Person(this.name); // just as bad
return new this.constructor(this.name);
};
with the code below (just replace this.constructor with Person)
Person.prototype.copy = function() {
// return new Person(this.name); // just as bad
return new Person(this.name);
};
Thank God that with ES6 classical inheritance purists can use language's native operators like class, extends and super and we don't have to see like prototype.constructor corrections and parent refereces.
Yes, it is necessary. When you do
Student.prototype = new Person();
Student.prototype.constructor
becomes Person
. Therefore, calling Student()
would return an object created by Person
. If you then do
Student.prototype.constructor = Student;
Student.prototype.constructor
is reset back to Student
. Now when you call Student()
it executes Student
, which calls the parent constructor Parent()
, it returns the correctly inherited object. If you didn't reset Student.prototype.constructor
before calling it you would get an object that would not have any of the properties set in Student()
.