2012-07-11 90 views
4

我正在研究骨幹應用程序。如何避免在Javascript中重複命名空間

我在不同的文件中構建了我的模型+集合+視圖。

這意味着像 function() { // all my code }()的解決方案在這裏並不適用

我添加了一個命名空間e.g App.ModelName App.Views.ViewName etc.

當我同一個命名空間內。我怎樣才能避免重複它。 即我怎麼能叫MODELNAME當我在我不斷重複完整的字符串即App.XXXX

感謝

回答

5

您有幾種選擇:

1)創建的每個函數的局部變量:)

App.ModelName.myFunction = function() { 
    var model = App.ModelName; 
    // then you can reference just model 
    model.myFunction2(); 
} 

2創建本地變量在每個文件範圍內:

(function() { 
    var model = App.ModelName; 

    model.myFunction = function() { 
     // then you can reference just model 
     model.myFunction2(); 
    } 


    // other functions here 

})(); 

3)使用的this值:

App.ModelName.myFunction = function() { 
    // call App.ModelName.myFunction2() if myFunction() was called normally 
    this.myFunction2(); 
} 
2

命名空間是時刻App.Views.ViewName

定義的函數是隻是全局範圍內的一個對象。

所以一個替代方案是使用with,雖然它有一些缺點。

但無論如何,看看這個例子:

window.test = { 
    a: function(){ console.log(this); return 'x'; }, 
    b: function(){ with (this){ alert(a()); }}  // <- specifying (this) 
}; 

window.test.b(); 
+2

_Using'不建議with',並在ECMAScript中5嚴格MODE_是被禁止的:https://developer.mozilla.org/en/JavaScript/Reference/Statements/with – 2012-07-11 05:25:43

+0

@AndrewD。呃,我警告了一些缺點...:P – 2012-07-11 05:30:17

1

如何將它們作爲參數?事情是這樣的:

(function(aM,aV) { 
    // use aM and aV internally 
})(App.Models,App.Views);