7

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

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?

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

我怎样才能防止这种情况发生?

4

1 回答 1

7

The object (reference) that's in the prototype is indeed shared across the instances, until such time as the reference itself is modified, as opposed to the contents of the object.

The way around it is to give each object its own .price property within the constructor:

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

The (default) primitive value you've supplied in Animal.prototype.priceb is also initially shared across instances, except that as soon as you modify it the instance acquires its own copy that shadows the original value from the prototype.

于 2013-06-13T13:46:47.937 回答