Search code examples
javascriptscopenestedobject-literal

How to access an outer member from a nested object literal?


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.
}

Solution

  • 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.
    };