柯里化是一种将使用多个参数的一个函数转换成一系列使用一个参数的函数的技术。
思想:利用闭包的机制,把一些内容事先存储和处理了,等到后期需要的时候拿来即用即可
需求:点击盒子后执行 fn 并把 this 指向 obj
由于 bind 不兼容 IE8 及以下,可以简单地用柯里化函数实现:
let obj = { x: 100 }; function fn(y, ev) {
// ev 代表事件对象 this.x += y; console.log(this); } /* * bind:预先处理内容 * @params: * func:要执行的函数 * context:需要改变的 this 指向 * args:给函数传递的参数 * @return: * 返回一个代理函数 */ function bind(func,context,...args) { return function () { fn.call(context,...args) } }; box.onclick = bind(fn,obj,200); console.log();
完整写法(把自己写的 bind 添加到 Function 原型上)
(function(proto){ function bind(context){ context = context || window; let _this = this; let outerArgs = [].slice.call(arguments,1); return function proxy() { let innerArgs = [].slice.call(arguments,0); let args = outerArgs.concat(innerArgs); _this.apply(context,args); } } proto.bind = bind })(Function.prototype)
可直接调用
box.onclick = fn.bind(obj,200)