开发者

Overwriting and Extending Prototype

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 properties.

But when extended(Gadget.prototype.price = 100) All instances have access.

function Gadget(name, color) {
this.name = name;
this.color = color;
this.brand = "Sony";
this.whatAreYou = function(){
return 'I am a ' + this.color + ' ' + this.name;
    }
}

myGadget = new Gadget();

myGadget.brand;


//Gadget.prototype.price = 100;

Gadget.prototype = {
 price: 100,开发者_Python百科
 rating: 3,

};

myGadget.price;
theGadget = new Gadget();
theGadget.price


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜