Function.prototype.bind 实现原理

1,731 阅读1分钟

Function.prototype.bind

方法说明

作用同call和apply一样,在指定对象上执行指定方法,不同点在于: 1、bind返回的是一个可执行函数 2、通过bind实现偏函数

源码关键点在于

1、闭包:缓存bind方法的参数(上下文对象和参数列表) 2、返回可执行函数 3、可执行函数的内部通过apply方法实现对象和方法的绑定 4、偏函数的关键在于闭包(缓存bind方法的参数)和第二次函数调用时参数的拼接

源码

Function.prototype.myBind = function (ctx, ...bindArgs) {
  // ctx、fnObj和args会形成闭包,fnObj是函数对象,即: test.bind(obj, arg1, arg2)中的test
  const fnObj = this
  return function (...fnArgs) {
    // 具体的函数绑定是通过apply方法实现的
    return fnObj.apply(ctx, [...bindArgs, ...fnArgs])
  }
}

// 示例
const obj = {
  name: 'I am obj'
}
function test (arg1, arg2) {
  return `${this.name}, ${arg1} ${arg2} !!`
}
// 绑定
const fn = test.bind(obj, 'hello', 'world')
const resFn = fn()
console.log(resFn)  // I am obj, hello world !!
// 偏函数
const pFn = test.bind(obj, 'hello')
const resPfn = pFn('world')
console.log(resPfn)    // I am obj, hello world !!