jonathanhuo11
jonathanhuo11

Reputation: 758

Javascript - "This" Keyword in Nested Functions

So I'm writing a webpage that contains a few nested objects.

var Object = {
    //first nested object
    nested1:{
        //nested object within nested1
        moreNested1:{
            //some values
            a:1,
            b:2
        }

    },

    //second nested object
    nested2:{
        //nested object within nested2
        moreNested2:{
            //some values
            x:1,
            y:2
        }

    }

};

As you can see, there are nested objects within nested objects, and there are values stored in moreNested1 and moreNested2.

My problem is trying to access a and b using a function that is located in moreNested2. Using the "this" keyword, I've written a function that tries to access and analyse a and b.

var Object = {
//first nested object
nested1:{
    //nested object within nested1
    moreNested1:{
        //some values
        a:1,
        b:2
    }

},

//second nested object
nested2:{
    //nested object within nested2
    moreNested2:{
        //some values
        x:1,
        y:2,

        //the function that accesses a and b from moreNested1
        foo:function() {
            //code that does not work
            var a = self.this.this.a;
            var b = self.this.this.b;

            //logs a and b
            console.log("a is " + a + " and b is " + b)

        }
    }

}

};

What I am trying to do is access a and b, two values stored within moreNested1, from a function in moreNested2. I just need a pointer on how to access some values in a situation like this.

Thank you. If you could rewrite the code and explain how and why it works, that would be wonderful.

Upvotes: 0

Views: 149

Answers (1)

prdnr
prdnr

Reputation: 43

Using 'this' won't help - I think you'll need to access the properties from the top level.

var thing = {
//first nested object
nested1:{
    //nested object within nested1
    moreNested1:{
        //some values
        a:1,
        b:2
    }

},

//second nested object
nested2:{
    //nested object within nested2
    moreNested2:{
        //some values
        x:1,
        y:2,

        //the function that accesses a and b from moreNested1
        foo:function() {
            var a = thing.nested1.moreNested1.a;
            var b = thing.nested1.moreNested1.b;

            //logs a and b
            console.log("a is " + a + " and b is " + b);

        }
    }

}
};

thing.nested2.moreNested2.foo();

You can run the code on JSFiddle: https://jsfiddle.net/a6ehfbe5/

Upvotes: 2

Related Questions