Looking at the following code, does theme[sprite].img get nested inside result[definition].data (as theme[sprite].img is inside theme[sprite]) as well as .img becoming its own element in result[definition]?
result[definition].data = theme[sprite];
result[definition].img = theme[sprite].img;
And if that is the case, what would happen if result[definition].data.img was deleted, would that also delete result[definition].img and even theme[sprite].img?
Thanks.
3 Answers 3
If you delete result[definition].data.img, then theme[sprite].img will be deleted too, because result[definiton].data and theme[sprite] are exactly the same single object. result[definition].img will retain its value beacuse result[definition] is separate object that have in its .img property copy of .img from another object.
This is not related in any way to nesting though. You simply reference the same object.
3 Comments
if
result[definition].data.imgwas deleted, would that also deleteresult[definition].img...
No. Objects are reference types. While the deletion will be observed from theme[sprite] , it will not be observed from result[definition].
Because theme[sprite] and result[definition].data are references to the same object, any changes made to that object are observable from any reference to it.
But because result[definition].img is a reference to a different object that happens to be referenced by the other, it is an entirely unique reference, and isn't affected by what happens in the other object.
+-----------+ +-----------+ | | sprite | | theme | |-------->| |\ v---deleting this reference... | | | | \ +-----------+ +-----------+ \ img +-----------+ ^ \ | | / \----> | | / | | / +-----------+ definition / ^ / / +-----------+ / / | | / / result | |-------/ img / | |----------------------------------/ +-----------+ ...doesn't affect this one-----------^ and vice versa
If you delete one of the img properties, the other stays intact.
2 Comments
The answers from Oleg and Cliffs are correct. However, I thought it might be useful, for the purposes of visualization, to see what these objects are actually shaped like:
var definition = "Foo",
sprite = "Bar",
result = {},
theme = {}
;
result[ definition ] = {}
// => result == { Foo : {} }
theme[ sprite ] = { img : "BAZ" }
// => theme == { Bar : { img : "BAZ" } }
result[ definition ].data = theme[ sprite ];
// => result == { Foo : {
// data : { img : "BAZ" }
// }
// }
result[ definition ].img = theme[ sprite ].img;
// => result == { Foo : {
// data : { img : "BAZ" },
// img : "BAZ"
// }
// }
delete result[ definition ].data.img;
console.log( result.[ definition ].data.img );
// => undefined
console.log( theme[ sprite ].img );
// => undefined
console.log( result[ definition ].img
// => "BAZ"