Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript nested object access root level

I have a nested object in javascript like this one:

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

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

Using a function i would have defined something like:

var self = this;

and used self but how can I do this in a literal object?

like image 872
Matteo Pagliazzi Avatar asked Nov 04 '22 17:11

Matteo Pagliazzi


1 Answers

The following code allows you to link to a parent element and avoid the parent showing up in a 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
}
like image 153
ChaosPandion Avatar answered Nov 09 '22 12:11

ChaosPandion