Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript object properties shared across instances?

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?

like image 958
Sebastian Hoitz Avatar asked Jun 13 '13 13:06

Sebastian Hoitz


1 Answers

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.

like image 180
Alnitak Avatar answered Oct 01 '22 14:10

Alnitak