Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
833 views
in Technique[技术] by (71.8m points)

javascript - 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,
 rating: 3,

};

myGadget.price;
theGadget = new Gadget();
theGadget.price
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...