2016-10-06 288 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;' –