我正在探索编写具有性能的Javascript模块的方法。
//My lib var MyModule = function(callback){ var count = 0; main(); //ugly in my opinion //Function I want to be public. function main(){ count ++; window.specialApi.doWorkAndCallback(secret); //… } //Function I want to keep private //It needs to access to counter variable (#closure) function secret(){ if(count === 2){ callback(); } } //private function //other private function //… }; //Later anyone else can use MyModule. MyModule(function(){console.log("ok");});
我在这里发现的问题是每次调用MyModule()时,JS VM都会重新解释整个函数列表,这对性能不利。
是否有允许我执行以下操作的模式:
由于
答案 0 :(得分:0)
以下函数创建并返回一个对象,该对象仅包含main
方法:
var MyModule = function(callback){
var count = 0;
var secret = function(){
if(count === 2){
callback();
}
}
var main = function(){
count ++;
window.specialApi.doWorkAndCallback(secret);
}
main();
return {
main: main
};
};
然后,您唯一需要做的就是调用此函数一次并将其返回值存储在变量上:
var module = MyModule(function(){console.log('ok');});
最后,每当您想要致电main
(并保留count
的旧值)时,只需执行以下操作:
module.main();
答案 1 :(得分:0)
//My lib
var modul =
{
count:0,
callback:{},
main: function(){
this.count ++;
window.specialApi.doWorkAndCallback(this.secret);
},
secret: function(){
if(this.count === 2){
this.callback();
}
}
};
modul.callback = function(){console.log("ok");};
modul.main();
modul.callback = function(){console.log("ok");};
modul.main();
modul.callback = function(){console.log("ok");};
modul.main();
modul.callback = function(){console.log("ok");};
modul.main();