Function.prototype.bind 实现原理

Function.prototype.bind

方法说明javascript

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

源码关键点在于java

一、闭包:缓存bind方法的参数(上下文对象和参数列表)
二、返回可执行函数
三、可执行函数的内部经过apply方法实现对象和方法的绑定
四、偏函数的关键在于闭包(缓存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 !!
相关文章
相关标签/搜索