javascriptoopinheritance

Why is it necessary to set “.prototype.constructor” of a constructor function?


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?


Solution

  • 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