函数柯理化

1.函数柯理化

大函数返回小函数

思想:利用闭包的机制(保存),将一些内容提前存储和处理,在某个阶段之后拿来用即可

 

2.应用

2.1 预处理内容返回一个代理函数

 /*
    * bind预先处理内容
    *   @params:
    *       func:要执行的函数
    *       context:要改变的this指向
    *       args:要给函数传递的参数
    *   @return
    *       返回一个代理函数
    * */
 const bind = function (fn,context,...args){
      return function proxy(){
           fn.call(context,...args)
      }
}

2.2 dom点击事件

const obj = {
    x:1000
}
function fn1(y){
     this.x += y
     alert(this.x)
}
// dom绑定事件 - 原生bind实现
btn.onclick = fn1.bind(obj,300)

// dom绑定事件 - call实现
btn.onclick = function (){
     fn1.call(obj,300)
}

// dom绑定事件 - bind预处理方式实现
btn.onclick = bind(fn1,obj,300)

2.3 定时器

// 定时器 - call处理
setTimeout(()=>{
      fn1.call(obj,300)
},3000)

// 定时器 - bind预处理方式实现
setTimeout(bind(fn1,obj,300),3000)

3. bind重写

~ function (proto){
    function bind(context,...outArgs){
         let _this = this
         return function proxy(...innerArgs){
              _this.call(context,...[...outArgs,...innerArgs])
         }
    }
}(Function.prototype)

4.add(1)(2)(3)...实现

 function add(){
       let args = [...arguments]
       let fn = function (){
           args = [...args,...arguments]
           return fn
       }
       fn.toString = function (){
           return args.reduce((pre,cur) => pre + cur,0)
       }
       return fn
}
const aa = add(1)(2)(3)(4)(5)
console.log(aa.toString())

  

posted @ 2021-08-18 18:46  卷叶小树  阅读(52)  评论(0编辑  收藏  举报