[英]Javascript object properties shared across instances?
我有一個示例類,它有兩個屬性:變量和對象:
var Animal, a, b;
Animal = (function() {
function Animal() {}
Animal.prototype.priceb = 4;
Animal.prototype.price = {
test: 4
};
Animal.prototype.increasePrice = function() {
this.price.test++;
return this.priceb++;
};
return Animal;
})();
a = new Animal();
console.log(a.price.test, a.priceb); // 4,4
b = new Animal();
console.log(b.price.test, b.priceb); // 4,4
b.increasePrice();
console.log(b.price.test, b.priceb); // 5,5
console.log(a.price.test, a.priceb); // 5,4 !! not what I would expect. Why not 4,4?
出於某種原因,這似乎有一種奇怪的行為。 看起來該類存儲了對象的引用,因此它在多個實例之間共享。
我怎樣才能防止這種情況發生?
原型中的對象(引用)確實在實例之間共享,直到引用本身被修改為止,而不是對象的內容 。
解決它的方法是在構造函數中為每個對象提供自己的.price
屬性:
function Animal() {
this.price = { test: 4 };
}
您在Animal.prototype.priceb
提供的(默認)原始值最初也是在實例之間共享的,除了一旦您修改它,實例就會獲取自己的副本,該副本會Animal.prototype.priceb
原型中的原始值。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.