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?
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
}
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With