Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
829 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 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...