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
barto point at the stringfoopoints to, but then you change whatbarpoints to when you reassignbar.In the second example, you assign
barto a new object, then you pointfooat that same object, then you reassignbarto a string.foois still pointed at the same object.Think of it like this:
bar = "something"is changing whatbarpoints 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.