In Javascript, objects can be nested, creating a hierarchical structure. However, accessing the parent object from a nested child object can be challenging.
Consider the following nested object:
obj: { subObj: { foo: 'hello world' } };
To reference the subobject within s, we use:
var s = obj.subObj;
Now, we want to obtain the parent object obj using s.
Unfortunately, there is no direct mechanism to retrieve the parent object from a child object in Javascript. This is because child objects have no knowledge of their parent's existence.
Alternative Solution
One workaround is to utilize a function to establish a parent-child relationship within nested objects. Extending the code above:
var main = {
name : "main object",
child : {
name : "child object",
parent : null
},
init : function() {
this.child.parent = this;
delete this.init;
return this;
}
}.init();
In the init function, we assign the parent object to the parent property within the child object. By calling this, we refer to the current object (ie. main) from within the nested child object. Finally, we remove the init function for code clarity.
Using this technique, we can now access the parent object from the child:
main.child.parent.name // returns "main object"
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3