2013-11-09 68 views
2
var Higher = { 

    hello: function(){ 
    console.log('Hello from Higher'); 
    } 

    Lower: { 
    hi: function(){ 

     //how to call the 'hello()' method from the Higher namespace? 
     //without hardcoding it, as 'Higher.hello()' 

     console.log('Hi from Lower'); 
    } 
    } 
} 

如何在不使用硬編碼的情況下從較高級別的名稱空間調用方法?請參考我想在另一個較低名稱空間中調用較高級別名稱空間方法的註釋。在javascript對象中訪問較高名稱空間

回答

3

JavaScript沒有名稱空間。您正在使用listeral對象,這很好,但無法訪問父對象。你可以像這樣使用閉包,但它有點冗長:

var Higher = new (function(){ 
    this.hello = function(){ 
     console.log('Hello from higher'); 
    } 

    this.Lower = new (function(higher){ 
     this.higher = higher; 

     this.hi = function(){ 
      this.higher.hello(); 

      console.log('Hi from lower'); 
     } 

     return this; 
    })(this); 

    return this; 
})(); 

Higher.hello(); 
Higher.Lower.hi();