In the following code, can the x member be accessed from the 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.
}
I don't think that sort of construct would make sense. I don't think there's anything stopping you from saying
In that scenario, how would you distinguish between the two parents?
The way to do it is probably with more of a constructor type function, with a parameter that gets assigned to outer.x and inner.whatever as needed.
Not in the construct you have there, no.
The main reason being that
outer
doesn't actually exist yet when you are insideinner
.If you changed the properties of
inner
to functions you could accessouter
at runtime, but it would be pretty ugly code.Consider using
new outer();
instead and build an object that way, then you can usethis
insideinner
, but then that is a completely different construct and would look something likeYou could also use a closure:
For a great article on closures check out the javascript garden
http://bonsaiden.github.com/JavaScript-Garden/#closures
In the way you put it - no.
You need two stages construction, this will work: