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 like weird behavior. It looks like the class stores a reference to the object, so that it is shared between multiple instances.

How can I prevent this?

+4
source share
1 answer

An object (link), which in the prototype is really shared between instances, until the link itself is changed, unlike the contents of the object.

The path to it is to provide each object with its own .price property inside the constructor:

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

The initial value (default) that you provided in Animal.prototype.priceb is also initially shared between the instances, except that as soon as you change it, the instance gets its own copy, which discards the original value from the prototype.

+4
source

Source: https://habr.com/ru/post/1486024/


All Articles