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

独自空忆成欢 提交于 2019-12-04 04:12:08

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!