Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>When you call:</p> <pre><code>x(a); </code></pre> <p>A few things are going on. First, the variable <code>a</code> (which simply holds a reference to an object) is passed <em>by value</em> to the function <code>x</code>. <code>x</code> now has its <em>own copy</em> of that reference, which happens to point to the same object in memory. Thus, any changes you make to properties on that referred object will affect other references to said object.</p> <p>When you call:</p> <pre><code>this.b = v; </code></pre> <p>You're again making a copy of <code>v</code> and setting it to <code>this.b</code>. Now, <code>a</code>, <code>v</code> and <code>this.b</code> are distinct variables in memory, all storing a reference to the same object.</p> <p>It seems what you're <em>attempting</em> to do is create a copy of the object itself, so you can manipulate one reference and not affect others. To do so, you'll need to create a <em>completely new</em> object in memory and copy over the properties.</p> <pre><code>var a = {"x":1} function x(v) { this.b = {}; // Create a new object this.b.x = v.x; // Copy over the x property // Copy over any other properties too this.b.x++; } x(a); alert(a.x); // The original object still has an x property of 1 </code></pre> <p>Since <code>this.b</code> is a new object and we've merely <em>copied over</em> properties from the object referred to by <code>v</code>, incrementing <code>this.b.x</code> will have no effect on whatever <code>v</code> is pointing to.</p>
    singulars
    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. 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