The other answers are more or less correct, but what they lack is the difference between
Main.prototype.foo = { bar: 1 };
and
Main.prototype.bar = 1;
In both cases, creating a new Main will create a new instance with a prototype chain with the foo or bar property. In both cases, the instance level property can be overridden without affecting other instances:
function Main() {}; Main.prototype.foo = { bar: 1 }; Main.prototype.bar = 1; a = new Main(); b = new Main(); a.foo = { bar: 2 }; console.log(a.foo.bar, b.foo.bar);
But when you create a new Main , the instance variable foo is a reference to a single object {bar:1} , which is common to all instances. Therefore, when you set a.foo.bar , you change the shared object, not the instance variable; the instance variable is a.foo reference.
You do not need to initialize the instance property in the constructor. A standard approach would be to set bar directly on the prototype, i.e. Main.prototype.bar = 1 , which will give you independent instance variables initialized to 1 . However, if you need a more complex data structure (an object, an array, or an instance of another class) for each instance, then you cannot create this as a property on the prototype, because you will be giving each instance a link to a common object, so the path inside the constructor is:
function Main() {
source share