2012-07-11 48 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);