Why is it necessary to set the prototype constructor?

前端 未结 14 1772
孤城傲影
孤城傲影 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.

提交回复
热议问题