有个需求:过一秒后执行fn,传递一个数字100,让fn中的this变为obj,输出"柯理化函数100"
var name = "window";
var obj = {name: "柯理化函数"};
function fn(e, num) {
console.log(this.name + num);
}
第一种思路,常规想法:
window.setTimeout(fn, 1000);//->this window ->windowundefined
window.setTimeout(fn,1000)
document.addEventListener("click",fn,false);
1)不灵活控制this
2)不能传递形参的值
window.setTimeout(function () {
fn.call(obj, 100);
}, 1000);
用珂理化函数来解决:
function bind(callBack, context) {
var outerArg = Array.prototype.slice.call(arguments, 2);
return function () {
var innerArg = Array.prototype.slice.call(arguments, 0);
var arg = innerArg.concat(outerArg);
callBack.apply(context, arg);
}
}
window.setTimeout(bind(fn, obj, 100, 200), 1000); //珂理化函数200
window.setTimeout(function () {
fn.apply(obj, [100, 200]); //珂理化函数200
}, 1000);
document.addEventListener("click", bind(fn, obj, 100, 200), false); //珂理化函数100
document.addEventListener("click", function (e) {
fn.apply(obj, [e, 100, 200]); //珂理化函数100
}, false);