跨实例共享的Javascript对象属性?

时间:2013-06-13 13:42:34

标签: javascript oop reference

我有一个示例类,它有两个属性:变量和对象:

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?

出于某种原因,这似乎有一种奇怪的行为。看起来该类存储了对象的引用,因此它在多个实例之间共享。

如何防止这种情况发生?

1 个答案:

答案 0 :(得分:5)

原型中的对象(引用)确实在实例之间共享,直到引用本身被修改为止,而不是对象的内容

解决方法是在构造函数中为每个对象赋予自己的.price属性:

function Animal() {
    this.price = { test: 4 };
}

您在Animal.prototype.priceb中提供的(默认)原始值最初在实例之间共享,除了一旦您修改它,实例就会获取自己的副本,该副本会影响原型的原始值。

相关问题