Overwriting and Extending Prototype

后端 未结 1 1961
隐瞒了意图╮
隐瞒了意图╮ 2020-12-21 15:30

I\'m not sure why when I overwrite the prototype below with an object(Gadget.prototype = { price: 100;}, only new instances of Gadget(theGadget) have access to the new prope

相关标签:
1条回答
  • 2020-12-21 16:00

    It seems pretty obvious to me - each object has a reference to its prototype which is set when the object is first constructed. If you set the prototype to something new:

    Gadget.prototype = {price: 100};
    

    you haven't changed any references to the old prototype. Only objects created afterwards will have their prototype set to the new value.


    Think of it like the difference between this:

    var a = {foo: true};
    var b = a;
    a = {baz: 'quux'}; // b refers to the original value of a
    

    and this:

    var a = {foo: true};
    var b = a;
    a.baz = 'quux'; // a and b refer to the same object
    
    0 讨论(0)
提交回复
热议问题