Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript access parent object attribute

I have a small issue in JS, I have two nested objects, and I would like to access a variable from the parent, like so:

var parent = {
    a : 5,

    child: {
        b : 3,
        displayA : function(){
            console.log(this.a);
            //undefined
            },

        displayB : function(){
            console.log(this.b);
            //displays 3
            }
        }
}

And I would just like to know how to make parent.child.displayA work :) (I have sub-objects that need access to a parent's variable)

Any help appreciated Thank you very much!

like image 568
Jo Colina Avatar asked Apr 19 '15 18:04

Jo Colina


2 Answers

You can use call to set the value of this:

parent.child.displayA.call(parent); // 5

You may also be interested in binding it:

parent.child.displayA = function(){
  console.log(this.a);
}.bind(parent);
parent.child.displayA(); // 5

Or you you can just use parent instead of this:

parent.child.displayA = function(){
  console.log(parent.a);
};
parent.child.displayA(); // 5
like image 143
Oriol Avatar answered Oct 20 '22 00:10

Oriol


You can use super.prop to access parent class properties. Of course, only if you are using ES6.

like image 39
Dmytro Medvid Avatar answered Oct 19 '22 23:10

Dmytro Medvid