如何从嵌套对象文字访问外部成员?

如何从嵌套对象文字访问外部成员?

问题描述:

在下面的代码中,是否可以从嵌套对象文字中访问x成员?

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