Javascript 覆盖和扩展原型
当我用一个对象(Gadget.prototype={ price:100;},只有Gadget的新实例(theGadget)可以访问新属性 但是当扩展(Gadget.prototype.price=100)时,所有实例都可以访问Javascript 覆盖和扩展原型,javascript,Javascript,当我用一个对象(Gadget.prototype={ price:100;},只有Gadget的新实例(theGadget)可以访问新属性 但是当扩展(Gadget.prototype.price=100)时,所有实例都可以访问 function Gadget(name, color) { this.name = name; this.color = color; this.brand = "Sony"; this.whatAreYou = function(){ return 'I am a
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
这对我来说似乎很明显-每个对象都有一个对其原型的引用,该引用是在首次构建对象时设置的。如果将原型设置为新的对象:
Gadget.prototype = {price: 100};
您尚未更改对旧原型的任何引用。只有后来创建的对象才会将其原型设置为新值
想象一下这两者之间的区别:
var a = {foo: true};
var b = a;
a = {baz: 'quux'}; // b refers to the original value of a
这是:
var a = {foo: true};
var b = a;
a.baz = 'quux'; // a and b refer to the same object
谢谢,我知道了这个概念,但是我说不清楚。你的解释很清楚。