views:

21

answers:

2

I'm not very sure about the question title, here is the situation, please see the following sample code

// original data
a = [
  {x : 1},
  {x : 2},
  {x : 3}
]

// assign to a variable  
b = a[0]

// do some change
b.x = 5

alert(a[0].x) 
// i thought it would still be 1 but it is 5, why???

*edit
thank you Amber and Andrei
i think i'll just write a function to loop through object properties to copy to a new object
thanks for the help again :)

+1  A: 

Objects are assigned by reference - which means that when you modify anything that references the object, it modifies it in every case where it's referenced.

b is merely storing a reference to the same object that a[0] is storing a reference to.

Amber
is there any way to avoid this happened?or every time i want to modify an object property i have to store it to another variable?
ben
so what if i need to copy the data stored in a to another obj without reference to a?
ben
You have to do what's called a 'deep copy' - http://snipplr.com/view/15407/deep-copy-an-array-or-object/
Amber
A: 

Think of it this way. a[0] is not the actual object {x : 1}. That object is somewhere in memory, and a[0] holds the memory address where that object is stored.

If you do a[0].x you dereference it. That means that you analyze the part before the . and see the address. You then fetch the object at that address and see if it has a property x and return it.

But if you do b=a[0] you're basically just copying the address of the object into b. So now you have two references (shortcuts to the memory address were the object is stored). If you now do b.x = 5 you look at what's before the .; it's b containing the address of the object, you fetch that object from memory, check if it has property x and change its value to 5. But a[0] points at the same address (so at the same object) so if you try to do a[0].x like before, you arrive at the address you just modified.

This is a bit of a simplified explanation, but you should think of variables holding objects as shortcuts to the memory address where the actual object is. And if you try to assign a variable the value of another object variable, your just making a new shortcut. This isn't true for variables holding numbers, so x actually holds the value 1, or 5, not an address. So if you do:

y = a[0].x;
y = 10;

a[0].x will not change its value .

Andrei Fierbinteanu
thanks Andrei :) i guess this means i can't just copy a while tree of a object node to another object, i'll have to assign values one by one :(
ben