编辑刚刚意识到我没有直接回答你的问题。对不起!但是希望这将帮助您了解一些替代技术。
这是我不时使用的一种技术,例如当我想添加一次属性或函数并且不允许以后覆盖它时。
var module = new function(){
var modules = {}; //internal module cache
return function(name, module){
//return all modules
if( !name ) return modules;
//return specific module
if( modules[name] ) return modules[name];
//return the module and store it
return modules[name] = module;
}
}
所以你可以像这样使用它:
//will store this since it doesn't exist
module('test', 'foo'); //Since 'test' doesn't exist on the internal 'modules' variable, it sets this property with the value of 'foo'
module('test'); // Since we aren't passing a 2nd parameter, it returns the value of 'test' on the internal 'modules' variable
module('test', 'bar'); //We are attempting to change the value of 'test' to 'bar', but since 'test' already equals 'foo', it returns 'foo' instead.
module(); // { 'test': 'foo' } //Here we aren't passing any parameters, so it just returns the entire internal 'modules' variable.
要看的关键是我们正在使用'new function()'。这是在赋值时完成的,因为我们真的希望“模块”成为内部函数,而不是外部函数。但是为了为内部“var modules”变量创建一个闭包,外部函数必须在赋值时执行。
另请注意,您也可以将外部函数编写为自执行:
var module = function(){
var modules = {};
//other stuff
}();