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

后端 未结 2 1902
[愿得一人]
[愿得一人] 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条回答
  •  -上瘾入骨i
    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

提交回复
热议问题