有個需求:過一秒後執行fn,傳遞一個數字100,讓fn中的this變爲obj,輸出"柯理化函數100"
var name = "window"; var obj = {name: "柯理化函數"}; function fn(e, num) { console.log(this.name + num); }
第一種思路,常規想法:javascript
window.setTimeout(fn, 1000);//->this window ->windowundefined window.setTimeout(fn,1000) document.addEventListener("click",fn,false);
1)不靈活控制this
2)不能傳遞形參的值java
window.setTimeout(function () { fn.call(obj, 100); }, 1000);
用珂理化函數來解決:app
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);