2016-10-06 240 views
1

我在这里工作昨天,一些旧的意大利面条jQuery代码转换为一个模块化的模式,然后我就开始思考这个问题:Javascript对象嵌套

我怎么会做这样的事情一些? 这可能吗?

var obj = { 
 
    insideObj1: { 
 
     moreInsideObj1: { 
 
      evenMoreInsideObj1: { 
 
      \t //How could I reference the "moreInsideObj1" from here 
 
      }, 
 
      evenMoreInsideObj2: { 
 
      \t //How could I reference the "insideObj1" from here 
 
      }, 
 
      evenMoreInsideObj2: { 
 
      \t //How could I reference the "obj" from here 
 
      } 
 

 
     }, 
 
     moreInsideObj2: { 
 
     \t //How could I do the same thing here 
 
     }, 
 
    }, 
 
    insideObj2: { 
 
    \t //Here I can use "this.insideObj1" right; 
 
    } 
 
};

**我是新来的JS和JQuery世界。

什么是这样的:

var obj = (function(){ 
 
    insideObj1: { 
 
     moreInsideObj1: { 
 
      evenMoreInsideObj1: { 
 
      \t //How could I reference the "moreInsideObj1" from here 
 
      }, 
 
      evenMoreInsideObj2: { 
 
      \t //How could I reference the "insideObj1" from here 
 
      }, 
 
      evenMoreInsideObj2: { 
 
      \t //How could I reference the "obj" from here 
 
      } 
 

 
     }, 
 
     moreInsideObj2: { 
 
     \t //How could I do the same thing here 
 
     }, 
 
    }, 
 
    insideObj2: { 
 
    \t //Here I can use "this.insideObj1" right; 
 
    } 
 
})();

回答

0

很容易:

var a = obj.insideObj1.moreInsideObj1.evenMoreInsideObj1; 
 
var b = obj.insideObj1.moreInsideObj1.evenMoreInsideObj2; 
 
var c = obj.insideObj1.moreInsideObj1.evenMoreInsideObj2; 
 
var d = obj.insideObj1.moreInsideObj2;

只需添加另一个点去更深入。

+0

是的,没关系,但是有可能做到像this.insideObj1.moreInsideObj1.evenMoreInsideObj1这样的事情,即使是最深的对象? –

+0

'this'关键字将始终引用第一个obj,或者它将引用第一个父级? –

+1

如果我理解正确,你想设置一个更深的物体等于更浅的物体?例如, 'obj.insideObj1.moreInsideObj1.evenMoreInsideObj1 = obj.insideObj1.moreInsideObj2;' –