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
super.prop
to access parent class properties. Of course, only if you are using ES6.In your example you haven't inheritance. You may do this
There is no general way for the object
child
to know that it is a member of the parent object. In your situation, you can make a direct reference to the parent object indisplayA()
, like so:You do not need to place parent in the global scope and use
window.parent
as another answer suggests; since you are declaringdisplayA
within the scope ofparent
, the function will close overparent
, and it will be accessible anywhere withinchild
. Since the closure contains a reference to theparent
object, you will see that changes toparent
will be reflected in the behaviour ofdisplayA
. For example, supposeparent
andchild
are defined as in your example, exceptdisplayA
is modified to useparent.a
. Then:All this being said, if you are trying to mimic OOP, then the other answer is right: you should read more about how the Javascript prototype chain works.
You can use
call
to set the value ofthis
:You may also be interested in binding it:
Or you you can just use
parent
instead ofthis
:Javascript is prototype based, it is not a regular OOP language like PHP or Java.
Take a look to Inheritance and the prototype chain and implement something like Simple Javascript inheritance.
You could probably access to parent through
window.parent
if it is in the global scope, but your example will not work in every case.I think it doesn't really make sence to do it like that since you can access child object only through its parent. so why add a mthod displayB to the child while you can add it to the parent which has access to all child properties.