Why is it necessary to set the prototype constructor?

前端 未结 14 1745
孤城傲影
孤城傲影 2020-11-22 02:54

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

// correct the          


        
相关标签:
14条回答
  • 2020-11-22 03:32

    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.

    0 讨论(0)
  • 2020-11-22 03:33

    EDIT, I was actually wrong. Commenting the line out doesn't change it's behavior at all. (I tested it)


    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().

    0 讨论(0)
提交回复
热议问题