How to access an external element from a literal of nested objects?

In the following code, can member x be accessed from a nested object literal?

var outer = { x : 0, inner: { a : x + 1, // 'x' is undefined. b : outer.x + 1, // 'outer' is undefined. c : this.x + 1 // This doesn't produce an error, } // but outer.inner.c is NaN. } 
+7
source share
4 answers

As you put it, no.

You need a two-stage design, this will work:

 var outer = { x : 0 }; // outer is constructed at this point. outer.inner = { b : outer.x + 1 // 'outer' is defined here. }; 
+9
source

Not in the design you are there, no.

The main reason is that outer doesn't actually exist when you are inside inner .

If you changed the inner properties to functions, you could access outer at run time, but that would be pretty ugly code.

Use new outer(); instead and create the object this way, then you can use this inside inner , but then it is a completely different construction and will look something like

 var outer = function() { this.x = 0; this.inner = { a: this.x + 1 }; }; var b = new outer(); console.log(b.inner.a); // 1 
+4
source

I do not think such a design made sense. I don’t think something is stopping you from telling you

 var outer2; outer2.inner = outer.inner; 

In this scenario, how would you distinguish between two parents?

The way to do this is probably with a larger constructor type function, with a parameter that is assigned to the external .x and internal. whatever is required.

0
source

You can also use closure:

 var outer = function outer() { var x = 0; return { inner : { a: x + 1 } } }; var b = outer(); console.log('a is ' + b.inner.a); //a is 1 

For a great closing article, check out the javascript garden

http://bonsaiden.github.com/JavaScript-Garden/#closures

0
source

All Articles