Reputation: 652
var list = [{name: 'foo'}, {name: 'bar'}];
var x = list[0];
x.name = 'baz'; // Changes name in list[0]
x = {name: 'baz'} // Doesn't change name in list[0] - PROBLEM
Looks like line #4 is creating a new variable. How to tell JavaScript to use existing variable x that was created in line #2?
Upvotes: 1
Views: 173
Reputation: 115910
The variable x
holds a reference to an object.
x.name = ...
changes a property on the particular object that x
refers to.
x = { ... }
changes which object x
refers to.
Here's the setup:
x ==> { old object } <== list[0]
When you do x = { .. }
, here's what happens:
x ==> { brand new object }
{ old object } <== list[0]
But you want it to do this (note: this never happens):
x ==> { brand new object } <== list[0]
{ old object } // referred to by no one! (will be garbage collected on the next sweep)
It seems you would like the statement x = { ... }
to completely replace the object that x
formerly referred to with a new object. You can't; JavaScript doesn't have any mechanism to allow this kind of replacement. Objects can't "be replaced" like my second example. You need to manually change each reference.
Instead, if you want to change the first element of list
, you need to do the replacement directly on the array. Namely, you must do list[0] = { ... }
, or list[0] = x
after you've already changed x
.
Upvotes: 4
Reputation:
// you are creating an array of two objects
var list = [{name: 'foo'}, {name: 'bar'}];
//assigning the first obj to a variable
var x = list[0];
//changing the property 'name' of the object held in variable x
x.name = 'baz'; //--Changes name in list[0]--(no it doesn't!!!, it only changes the property of the object held in variable x!, not the one in the array)
//now you are assigning a new object to that variable!!!
x = {name: 'baz'}
Upvotes: 1
Reputation: 13672
x is not a pointer to the first element in the list. Thus, when it is changed, it will not affect the first element in your list. If you want it to change you will need to explicitly do so:
var list = [{name: 'foo'}, {name: 'bar'}];
var x = list[0];
x.name = 'baz'; // Changes name in list[0]
x = {name: 'baz'}; // Doesn't change name in list[0] - PROBLEM
list[0] = x; // now list[0] is {name: 'baz'}
Upvotes: 1