I understand the following property of the javascript language:
var bar = 1;
var foo = bar;
bar = "something entirely different";
// foo is still 1
However, when trying to apply this logic to an object it seems to act differently:
var bar = {};
bar.prop = 1;
var foo = bar;
bar.prop = "something entirely different";
// foo.prop now changes to "something entirely different"
// but...
bar = "no longer an object";
// now foo remains an object with the prop property
Can someone tell me what's happening and why there is a difference?
That's correct. When you assign a variable to an object, you're really creating a second reference to that object. In the first case, what you're doing is assigning bar
to point at the string foo
points to, but then you change what bar
points to when you reassign bar
.
In the second example, you assign bar
to a new object, then you point foo
at that same object, then you reassign bar
to a string. foo
is still pointed at the same object.
Think of it like this: bar = "something"
is changing what bar
points to, not changing the actual object {}
to a string.
This article is a fairly good explanation of what you're seeing. I'm looking for even better / more authoritative references, however.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With