JavaScript

实现函数的bind方法

2021-02-02  本文已影响0人  埼玉的头发

思路:
返回一个新函数,新函数内部调用了apply。
目的:
使改变函数的this指向(执行上下文)时,函数的执行变得可控。

   // bind是函数的方法,所以要添加到Function的原型上
    Function.prototype.myBind = function(context) {
      // 获取除了context的其他参数
      let args1 = Array.prototype.slice.call(arguments, 1)
      // 缓存this
      let that = this
      // 返回一个待执行的函数
      return function() {
        // 获取待执行函数全部参数
        let args2 = Array.prototype.slice.call(arguments)
        // 合并两个方法的参数
        let args = args1.concat(args2)
        return that.apply(context, args)
      } 
    }

    const obj = {
      name: 'mayun'
    }
    function demo() {
      console.log('也执行了',arguments)
      return 'success'
    }
    let demoFun = demo.myBind(obj, 1, 2, 3)
    console.log(demoFun)
    demoFun()
    console.log(demoFun())
上一篇 下一篇

猜你喜欢

热点阅读