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.
}
In the way you put it - no.
You need two stages construction, this will work:
var outer = { x : 0 };
// outer is constructed at this point.
outer.inner = {
b : outer.x + 1 // 'outer' is defined here.
};
Not in the construct you have there, no.
The main reason being that outer
doesn't actually exist yet when you are inside inner
.
If you changed the properties of inner
to functions you could access outer
at runtime, but it would be pretty ugly code.
Consider using new outer();
instead and build an object that way, then you can use this
inside inner
, but then that is a completely different construct and would 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
I don't think that sort of construct would make sense. I don't think there's anything stopping you from saying
var outer2;
outer2.inner = outer.inner;
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.
You could also use a 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 article on closures check out the javascript garden
http://bonsaiden.github.com/JavaScript-Garden/#closures