Object.create changes prototype.constructor to parent constructor, but upon child instantiation, child constructor runs

后端 未结 2 1930
[愿得一人]
[愿得一人] 2021-01-15 09:26

I\'ve created an example to illustrate:

// this is the parent class
function animal() { console.log(\'animal constructor\') }

// allow animals to walk
anima         


        
2条回答
  •  日久生厌
    2021-01-15 10:00

    The constructor property is just a simple property of the prototype object. There is nothing magically happening with it behind the scenes. It's a property that can be overridden and reset, but it doesn't affect anything else.

    So when you do this:

    cat.prototype = Object.create(animal.prototype);
    

    you are overriding the entire prototype property of the function cat with a complete new object derived from the prototype object of animal. But since the constructor property is just a normal property of the prototype object, it will get overridden as well.

    And yes, when implementing inheritance, the line

    Class.prototype.constructor = Class;
    

    is commonly added to restore the constructor property to its original value and to kind of undo the "damage" that was done by this inheritance pattern.

    So in your case, you would need to add the following line:

    cat.prototype = Object.create(animal.prototype);
    cat.prototype.constructor = cat;  //  <---- add this
    

提交回复
热议问题