Yoav Kadosh Yoav Kadosh - 5 months ago 10
Javascript Question

Instantiating a New Object References The Same Property

Why when I instantiate a new object in JavaScript that has another object as one of its properties, does it always reference the same object?

For example

function test() {}

test.prototype.state = {
num: 0
};

var obj1 = new test();
var obj2 = new test();

obj1.state.num = 1;

console.log(obj1.state.num,obj2.state.num); // Outputs 1 1 instead of 1 0


Also, what would be the appropriate way to make it create a new object property every time it is instantiated?

Answer

Because that's what the prototype is: a shared object among all instances. You're explicitly creating the { num: 0 } object only once, so it will exist only once. Javascript doesn't clone it for you when instantiating a new test. Usually the prototype is used for functions, where this doesn't make any difference. If you want instance specific attributes, you need to create them in the constructor function:

function test() {
    this.state = { num: 0 };
}