JS开发中,经常会遇到在执行一个函数时,需要设定该函数的context。比如,在使用window.setInterval(func, 1000)时,很多时候需要提供func函数的执行环境,这里是一个解决方案的例子,如下:
var bind = function(obj, func){
return function(){
func.apply(obj,arguments);
};
};
var Module = {};
Module.test = function(){
this.num = 0;
this.init();
};
Module.test.prototype = {
init:function(){
setInterval(bind(this, this.add), 1000);
},
add:function(){
alert(this.num++);
}
};
new Module.test();