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!
displayAfunction, you're referencing "this" and attempting to access its "a" attribute. The call to "this" here refers to the child object and not the parent. If you used a constructor you could pass in the context (this) of its parent to the child object. Or you could use the call or bind methods.