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

跨实例共享的Javascript对象属性?,javascript,oop,reference,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 t

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

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
中提供的(默认)原语值最初也会在实例之间共享,只是只要您修改它,实例就会获得自己的副本,而该副本会将原语值与原语值进行隐藏。

“!?实例会获得自己的副本!”
-仅当属性不是对象(作为引用传递)时@bortunac,即使该属性是对对象的引用。如果您有
Animal.prototype.obj={}
并在实例中覆盖
obj
,则该实例现在有自己对新对象的引用。@Alnitak。。。是的,你的权利。。。我只想强加一个常见的错误
o1=新动物;o2=新动物;o1.对象属性1=1
now
o2.obj.prop1==1