Dänu Dänu - 4 months ago 13
Javascript Question

Javascript objects: get parent

I got some question about nested javascript objects (is it me, google or is javascript quite poorly documented?). Now, I got the following (nested) object:

obj: { subObj: { foo: 'hello world' } };


next thing I do is to reference the subobject like this:

var s = obj.subObj;


now what I would like to do, is to get a reference to the object obj out of the variable s.
Something like:

var o = s.parent;


Is this somehow possible?

Answer

No. There is no way of knowing which object it came from.

s and obj.subObj both simply have references to the same object.

You could also do:

var obj = { subObj: {foo: 'hello world'} };
var obj2 = {};
obj2.subObj = obj.subObj;
var s = obj.subObj;

You now have three references, obj.subObj, obj2.subObj, and s, to the same object. None of them is special.