Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>The other answers are more or less correct, but what they're missing is that there's a difference between</p> <pre><code>Main.prototype.foo = { bar: 1 }; </code></pre> <p>and</p> <pre><code>Main.prototype.bar = 1; </code></pre> <p>In both cases, instantiating a new <code>Main</code> will create a new instance with, in its prototype chain, a property <code>foo</code> or <code>bar</code>. In both cases, the instance-level property can be redefined without affecting other instances:</p> <pre><code>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); // 2 1 a.bar = 2; console.log(a.bar, b.bar); // 2 1 </code></pre> <p>But when you instantiate a new <code>Main</code>, the instance variable <code>foo</code> is a <em>reference</em> to a single object, <code>{bar:1}</code>, which is shared among all instances. So when you set <code>a.foo.bar</code>, you're changing the common object, not an instance variable; the instance variable is the reference <code>a.foo</code>.</p> <p>You don't have to initialize the instance property in the constructor. The standard approach would be to set <code>bar</code> directly on the prototype, i.e. <code>Main.prototype.bar = 1</code>, which would give you independent instance variables initialized to <code>1</code>. However, if you need a more complex data structure (an object, an array, or an instance of another class) on a per-instance basis, then you can't create this as a property on the prototype, because you'll be giving every instance a reference to a common object - so inside the constructor is the way to go:</p> <pre><code>function Main() { // instance-level object this.foo = { bar: 1 }; } </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload