我不知道为什么当我用一个对象覆盖下面的原型(prototype)时(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 ' + 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
最佳答案
这对我来说似乎很明显 - 每个对象都有一个对其原型(prototype)的引用,该原型(prototype)是在第一次构造对象时设置的。如果您将原型(prototype)设置为新的东西:
Gadget.prototype = {price: 100};
您尚未更改对旧原型(prototype)的任何引用。只有后来创建的对象才会将其原型(prototype)设置为新值。
把它想象成这之间的区别:
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
关于javascript - 重写和扩展原型(prototype),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7542036/