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

后端 未结 2 1903
[愿得一人]
[愿得一人] 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
    
    0 讨论(0)
  • 2021-01-15 10:08

    Think about the line:

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

    Object.create(animal.prototype) will simply return an object that has no properties itself but whose prototype is given by animal.prototype. Therefore looking up the constructor property on this object will simply return the value held in animal.prototype.constructor.

    Since the above line is assigning a reference to this newly created object to cat.prototype (and hence overwriting whatever was previously held in cat.prototype), of course you'd expect cat.prototype.constructor to be equal to animal.prototype.constructor.

    As you mentioned above, you can side-step this 'issue' using something like:

    cat.prototype.constructor = cat;
    

    reference for Object.create(): https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/create

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