5

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?

3
  • I don't believe you can. I don't know of the post off the top of my head, but I remember reading this on StackOverflow recently. Can you define that object as a function, instead of an object literal? Commented Aug 29, 2012 at 14:26
  • 2
    You can’t. But an object is not without reference, so somewhere you must have a reference to the object you are in, no? Commented Aug 29, 2012 at 14:33
  • 1
    This is also the reason why nodes and such need to have an explicit reference back to parentNode. Commented Aug 29, 2012 at 14:46

2 Answers 2

2

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
}
Sign up to request clarification or add additional context in comments.

Comments

0

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

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

then you could do something like:

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

Obviously there are smarter ways to do it (e.g. pass the name through the function params) but this is the general pattern.

2 Comments

Question: but how can I do this in a "literal object"
You can't, that's why I said to do it the way I suggested.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.