我在Stoyan Stefanov的书中读过关于单一var模式的书. JSLint也很好.
但我在我的代码中注意到我可能会重载此模式.它发生在整个我的.js文件中,整个脚本只是一个大变量.
例如:
$(function(){
var
some_var1 = 'some_value',
some_var2 = { /* some other value */},
// more and more vars
tiny_fun = function(){ /* some tiny helper function */ },
tiny_fun2 = function(){ /* another tiny helper function */},
// more tiny functions
Constructor1 = function(){ /* Some Constructor */ },
Constructor2 = function(){ /* Another Constructor */ },
script_body = (function(){
// main script - 'script body'
var c1 = new Constructor1();
c1.some_method();
// and other client code
})(); //: script_body
});
这不好吗?也许我误解了这个单变量模式,应该只将其用于变量 – 以防止使用全局变量?
最佳答案 如果您只对私有访问元素进行分组,则完全没有问题.请记住,您不能使用var声明公共访问元素(全局范围是一个例外).