Function.prototype.bind 实现原理

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 !!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值