JavaScript Parent Access Attribute

I have a little problem in JS, I have two nested objects, and I would like to access the variable from the parent, for example:

var parent = { a : 5, child: { b : 3, displayA : function(){ console.log(this.a); //undefined }, displayB : function(){ console.log(this.b); //displays 3 } } } 

And I just wanted to know how to make parent.child.displayA work :) (I have sub-objects that need access to the parent variable)

Any help appreciated Thank you so much!

+7
javascript object oop
source share
6 answers

You can use call to set this value:

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

You may also be interested in binding to it:

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

Or you can just use parent instead of this :

 parent.child.displayA = function(){ console.log(parent.a); }; parent.child.displayA(); // 5 
+10
source share

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

+2
source share

Javascript is a prototype based , it is not a regular OOP language like PHP or Java.

Take a look at Inheritance and the prototype chain and implement something like Simple Javascript Inheritance .

Perhaps you can access the parent through window.parent if it is in the global scope, but your example will not work in each case.

+1
source share

There is no general way for a child object to know that it is a member of the parent object. In your situation, you can directly reference the parent in displayA() , for example:

 displayA : function(){ console.log(parent.a); } 

You do not need to place the parent in the global scope and use window.parent as the other answer suggests; since you declare displayA within parent , the function will close over parent , and it will be available anywhere inside child . Since the closure contains a reference to the parent object, you will see that changes to parent will be reflected in the behavior of displayA . For example, suppose parent and child defined as in your example, except for displayA , to use parent.a . Then:

 parent.child.displayA(); //=> 5 parent.a = 10; parent.child.displayA(); //=> 10 

All this, if you are trying to simulate OOP, then the other answer is right: you should learn more about how the Javascript prototype chain works.

0
source share

I think this is actually not the case, because you can only access the child through your parent. so why add midd displayB to the child, while you can add it to the parent that has access to all the child properties.

0
source share

In your example, you have no inheritance. You can do it

 ... displayA : function(){ console.log(parent.a); // 5 }, ... parent.child.parent = parent; parent.child.displayA(); 
0
source share

All Articles