Search code examples
javascriptfunctionscopestructure

javascript: access to parent object in structure from the scope of the function in structure


Tell me how from the scope of the function (in structure) to access the elements of its parent (in structure)?

For example:

var mystruct = {
    element1: 10,
    element2: 'test',
    element3: {
        sub1: 'data',
        sub2: function(){
            return this;
        }
    },
};

var res = mystruct.element3.sub2();

result:

res = {sub1: 'data', sub2: f}

But how does the function mystruct.element3.sub2 access to the element mystruct.element1?

For example:

sub2: function(){
    return this.parent.element1;
}

result:

res = 10

Method:

sub2: function(){
    return mystruct.element1.sub1;
}

not suitable, because in the scope of the function I do not know about the mystruct


Solution

  • You can use an Immediately Invoked Function Expression (IIFE) to create element3, so you can save the parent object in a variable and then use it accordingly.

    var mystruct = {
        element1: 10,
        element2: 'test',
        element3: (function () {
            // save the reference you want to access later
            var parent = this;
            // create and return the object that you want to assign to 'element3'
            return {
                sub1: 'data',
                sub2: function() {
                    // use the saved reference
                    return parent.element1;
                }
            }
        })()  // NOTE: immediately invoke the function to return the correct object
    };
    

    And afterwards you can use it as you wanted it:

    mystruct.element3.sub2();  // will return 10
    

    Or you can just use it's variable name:

    sub2: function () {
        return mystruct.element1;
    }