Why is it necessary to set the prototype constructor?

前端 未结 14 1747
孤城傲影
孤城傲影 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: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().

提交回复
热议问题