0

The title might seems weird, but I don't really know how to describe this situation as I'm a beginner in JavaScript.

Here's the code :

a={};
var b=a;
b['a']='x';
console.log(a);

the result will be:

Object { a="x"}

shouldn't it be a blank object because I set 'x' to variable b only ?

Edxz
  • 823
  • 2
  • 8
  • 22

2 Answers2

7

a contains a reference to an object, like this:

+-----+        +--------------+
|  a  |------->| (the object) |
+-----+        +--------------+

So when you do:

var b = a;

Now you have two variables referring to the same object.

+-----+
|  a  |---+
+-----+   |    +--------------+
          +--->| (the object) |
+-----+   |    +--------------+
|  b  |---+
+-----+

So naturally, any changes you make to that object (adding a property to it, in your case) are visible through either reference.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • 1
    never expected such a detail explanation,thank you very much, finally understand this :D – Edxz Sep 12 '13 at 17:02
  • Sorry for nitpicking, but why exactly does `b` have an almost twice as long reference line? Couldn't you better make them as long? :P – BalusC Sep 12 '13 at 17:22
  • @BalusC: :-) I find it surprisingly hard to "see" ASCII-art, even though I love it. I've removed the extra line, thanks. – T.J. Crowder Sep 12 '13 at 17:23
0

b is a reference to a so that is a normal behavior. To avoid that you need to make a clone. For example, using jQuery framework you could simple do: var b = $.extend(true, {}, a};

letiagoalves
  • 11,224
  • 4
  • 40
  • 66