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!
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
You can use super.prop
to access parent class properties. Of course, only if you are using ES6.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With