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:
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 in displayA()
, like so:
displayA : function(){
console.log(parent.a);
}
You do not need to place parent in the global scope and use window.parent
as another answer suggests; since you are declaring displayA
within the scope of parent
, the function will close over parent
, and it will be accessible anywhere within child
. Since the closure contains a reference to the parent
object, you will see that changes to parent
will be reflected in the behaviour of displayA
. For example, suppose parent
and child
are defined as in your example, except displayA
is modified to use parent.a
. Then:
parent.child.displayA(); //=> 5
parent.a = 10;
parent.child.displayA(); //=> 10
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.