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

Seb*_*itz 4 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?
Run Code Online (Sandbox Code Playgroud)

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

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

Aln*_*tak 5

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

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

function Animal() {
    this.price = { test: 4 };
}
Run Code Online (Sandbox Code Playgroud)

你所提供的(默认)原始值Animal.prototype.priceb开始跨实例只要你修改的情况下获取其自身拷贝的影子原型原值共享,不同的是.