How to access an outer member from a nested object

2019-04-07 03:50发布

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

4条回答
够拽才男人
2楼-- · 2019-04-07 04:04

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.

查看更多
走好不送
3楼-- · 2019-04-07 04:07

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
查看更多
神经病院院长
4楼-- · 2019-04-07 04:12

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

查看更多
Summer. ? 凉城
5楼-- · 2019-04-07 04:14

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.
};
查看更多
登录 后发表回答