Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Objects (including arrays) are stored as references. Primitives (including numbers) are stored as values.</p> <p><code>new person()</code> creates a new person, with a reference to an empty array. You assign this object (not class, object!) as a prototype for <code>kevin</code>.</p> <p><code>foo1.a</code> does not exist, so <code>a</code> is looked up the prototype chain, where we find the empty array we found before. When we modify the contents of this array, we still have undefined <code>foo1.a</code>. You have changed the array contents, but you have not changed the value of the reference (not on the prototype, and certainly not on <code>foo1</code>).</p> <p><code>foo2.a</code> also does not exist, and thus <code>a</code> is again looked up on the prototype - finding the very same array from before (which now contains some changes from when we were accessing it through <code>foo1</code>).</p> <p>In contrast, <code>foo1.b = ...</code> will define a new value on <code>foo1</code>. The next lookup of <code>b</code> will not travel up the prototype chain. In addition to this, numbers can't be changed, just overwritten, so you can't get into the situation where content changes and identity doesn't, like with objects.</p> <p>So - you have two different phenomena here, and both of them are usual suspects for the kind of behaviour you're asking about. Here, specifically, the prototypal inheritance is the culprit, but that only happens in JavaScript and similar languages (of which there are not too many). In most other cases, similar problems are caused by the reference/value distinction.</p>
 

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