Root Access Level of Javascript Nested Objects

I have a nested object in javascript similar to this:

{
nameRoot: "my object",
sub: {
  nameSub: "my sub object"
}
}

I want to access nameRoot from a function defined in sub.

Using a function, I would define something like:

var self = this;

and used self, but how to do it in a literal object?

+5
source share
2 answers

The following code allows you to reference the parent element and avoid the appearance of the parent element in the for-in loop.

var parent = { a: 1 };
var child = { b: 2 };

Object.defineProperty(
    child, 'parent', 
    { value: parent, 
      enumerable: false }
);

parent.child = child;

child.performAction = function() {
    console.log(this.parent.a) // 1
}
+1
source

So the best way to do this is with a w / function scope.

function myFunc(){
   this.nameRoot = "my object";
}

then you can do something like:

var func = new myFunc();
func.sub = new myFunc();
func.sub.nameRoot = "my sub object";

Obviously, there are more reasonable ways to do this (for example, pass a name through function parameters), but this is a common template.

0
source

All Articles