Can someone give the best explanation of what is going on here:
var o = {
name: "jack"
};
var z = {
name: o.name
};
o = {};
alert(z.name); // expected undefined, shows "jack" instead
Are object properties just references? Destroying the object o doesn't seem to destroy the referenced object (in this case the string "jack"). Or, is it the case that the "jack" referenced by o.name is actually destroyed but that z.name created a copy of o.name?
Best
// consider this too
var o = {
foo: function () {
return "hello";
}
};
var z = {
m: o.foo
};
o = {};
alert(z.m()); // hello is displayed
3 Answers 3
You might find this more interesting.
var o = {
name: "Jack"
};
var z = {
name: o
};
//Above assignment of 'o' to z.name will create a new alias to object 'o'.
//So both 'o' and 'z.name' point to same object.
//When you change value inside 'o' it will still reflect in 'z.name'
//because both point to same object
o.name="Jill";
console.log(z.name.name); // Logs : Jill and not Jack.
// Now, here you are actually assigning a new object to 'o'.
// This means now 'o' refers to a new object. But this will no way affect
// the 'z.name' reference, it still points to same object.
o = { name : "Joe"};
console.log(z.name.name); // Logs : Jill again and not Joe
1 Comment
Strings are copied by value, not reference.
Even if that wasn't the cause, objects are only handled by reference so overwriting o with a reference to a new object wouldn't change any references to the old object.
1 Comment
Are object properties just references?
Yes and No.
They are not references in the meaning of "live updating", when you change (or delete) o.name then z.name won't be altered.
They are references in the meaning of binding some arbitrary value (with a property name) to an object. These values will exist on their own, forgotten (deleted from memory) only when no one does have a handle on them any more.
You might be interested in the overview of Objects in the EcmaScript specification.
z.name created a copy of o.name?
Yes. JavaScript differentiates between objects (with changeable properties) and primitive values (which are immutable). All of these are copied by value - there is no call-by / assign-by reference in JS - and so strictly speaking both z.name and o.name reference two different values. However the object values are so-called reference values which reference the same property-value structures in memory whenever they are copied.
Comments
Explore related questions
See similar questions with these tags.