我在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模式,应该只对变量使用它——以防止使用全局变量?
如果只对私有访问元素进行分组,则根本没有问题。请记住,不能使用var
声明公共访问元素(全局作用域是一个例外)。