Why is it necessary to set the prototype constructor?

前端 未结 14 1749
孤城傲影
孤城傲影 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:16

    It is necessary. Any class in class inheritance must has its own constructor, so as in prototype inheritance.It is also convenient for object construction. But the question is unnecessary and what is necessary is understanding in JavaScript world effect of calling function as constructor and rule of resolving object property.

    Effect of executing function as constructor with expression new ( [ parameters] )

    1. a object whose type name is the function name is created
    2. inner properties in the function attaches to the created object
    3. property prototype of the function attaches automatically to the created object as prototype

    Rule of resolving property of object

    • The property will not only be sought on the object but on the prototype of the object, the prototype of the prototype, and so on until either a property with a matching name is found or the end of the prototype chain is reached.

    Basing on these underlying mechanisms, statement .prototype.constructor = equals in term of effect to attach constructor in constructor body with expression this.constructor = . The constructor will be resolved on the object if second utterance while on object's prototype if first utterance.

提交回复
热议问题