Home > Web Front-end > JS Tutorial > How can I access the parent object of a nested object in JavaScript?

How can I access the parent object of a nested object in JavaScript?

Susan Sarandon
Release: 2024-10-25 03:29:29
Original
387 people have browsed it

How can I access the parent object of a nested object in JavaScript?

Getting Parent Object of a Nested Object in JavaScript

When working with nested JavaScript objects, it can be useful to access the parent object of a given nested object. However, this is not directly possible within JavaScript.

Nested objects (child objects) lack an explicit reference to their parent objects (parent objects). This means that a child object cannot access the properties or methods of its parent object directly.

For example, given the following object hierarchy:

<code class="js">obj: { subObj: { foo: 'hello world' } };</code>
Copy after login

Assigning a reference to the subobject:

<code class="js">var s = obj.subObj;</code>
Copy after login

There is no built-in method for s to directly access the obj object.

One approach to address this is to manually set a reference to the parent object in the child object. This can be done using a function:

<code class="js">var main = {
    name : "main object",
    child : {
        name : "child object"
    },
    init : function() {
        this.child.parent = this;
        delete this.init;
        return this;
    }
}.init();</code>
Copy after login

Within the init function, we assign the this (the main object) to a property named parent within the child object. This allows s to access obj:

<code class="js">s.parent.name  // Output: "main object"</code>
Copy after login

Keep in mind that this approach involves modifying the original object structure and requires manual initialization. However, it provides a way to access the parent object from a nested object in JavaScript.

The above is the detailed content of How can I access the parent object of a nested object in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template