Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
181
rated 0 times [  187] [ 6]  / answers: 1 / hits: 62038  / 13 Years ago, sat, december 10, 2011, 12:00:00

In the section about inheritance in the MDN article Introduction to Object Oriented Javascript, I noticed they set the prototype.constructor:



// correct the constructor pointer because it points to Person
Student.prototype.constructor = Student;


Does this serve any important purpose? Is it okay to omit it?


More From » oop

 Answers
10

It's not always necessary, but it does have its uses. Suppose we wanted to make a copy method on the base Person class. Like this:



// define the Person Class  
function Person(name) {
this.name = name;
}

Person.prototype.copy = function() {
// return new Person(this.name); // just as bad
return new this.constructor(this.name);
};

// define the Student class
function Student(name) {
Person.call(this, name);
}

// inherit Person
Student.prototype = Object.create(Person.prototype);


Now what happens when we create a new Student and copy it?



var student1 = new Student(trinth);  
console.log(student1.copy() instanceof Student); // => false


The copy is not an instance of Student. This is because (without explicit checks), we'd have no way to return a Student copy from the base class. We can only return a Person. However, if we had reset the constructor:



// correct the constructor pointer because it points to Person  
Student.prototype.constructor = Student;


...then everything works as expected:



var student1 = new Student(trinth);  
console.log(student1.copy() instanceof Student); // => true

[#88634] Thursday, December 8, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
turnerf

Total Points: 620
Total Questions: 101
Total Answers: 109

Location: French Polynesia
Member since Tue, Jul 7, 2020
4 Years ago
turnerf questions
;