最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

oop - Javascript object properties shared across instances? - Stack Overflow

programmeradmin2浏览0评论

I have an example class that has two properties: a variable and an object:

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?

For some reason, this seems to have a weird behavior. It looks like the class stores a reference to the object, so that it is shared across multiple instances.

How can I prevent that from happening?

I have an example class that has two properties: a variable and an object:

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?

For some reason, this seems to have a weird behavior. It looks like the class stores a reference to the object, so that it is shared across multiple instances.

How can I prevent that from happening?

Share Improve this question asked Jun 13, 2013 at 13:42 Sebastian HoitzSebastian Hoitz 9,42314 gold badges63 silver badges77 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 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.

发布评论

评论列表(0)

  1. 暂无评论