Where the __proto__ is pointing when we change the prototype of the parent object?

前端 未结 1 1035
野性不改
野性不改 2021-01-22 00:11

Normally when we create a new object using \"new\" keyword, actually the __proto__ property of the created object is pointing to the prototype

相关标签:
1条回答
  • 2021-01-22 00:45

    When you are using new operator to create an Object, a new JavaScript Object will be created and its internal __proto__ property will be set to the prototype of the function.

    At this point

    console.log(myfunc.prototype);
    

    is referring to the object

    { name: 'myfunction' }
    

    So, when you do

    var child = new myfunc();
    

    internally

    child.__proto__ = myfunc.prototype;
    

    is happening. Now, the important thing to understand here is, in JavaScript, when you use assignment operator, the left hand side name will be just made to refer the result of the right hand side expression. So, in this case, child.__proto__ is just another name for the object referred by the name myfunc.prototype. Now, both child.__proto__ === myfunc.prototype and are referring to { name: 'myfunction' }. That is why child.__proto__ === myfunc.prototype is returning true.

    Now, when you do

    myfunc.prototype = {};
    

    you are making myfunc.prototype refer the new object {}, but the child.__proto__ is still referring to the old object { name: 'myfunction' }. That is why child.__proto__ === myfunc.prototype returns false and child.name still says myfunction.

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