前端小技巧: TS实现bind函数,call函数,以及apply函数

本文详细解释了JavaScript中bind、call和apply的用法,以及它们如何影响函数的this值。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

bind 函数实现

  • 返回一个新函数,但是不执行

    Function.prototype.customBind = function (context:any, ...bindArgs: any[]) {
      // context 是bind传入的this
      // bindArgs 是bind传入的各个参数
      const self = this // 当前函数本身
      return function(...args:any[]) {
        const newArgs = bindArgs.concat(args)
        return self.apply(context, newArgs)
      }
    }
    
    function fn(this:any, a:any, b:any, c:any) {
      console.info(this, a, b, c)
    }
    
    const fn1 = fn.customBind({x: 100}, 10)
    fn1(20, 30)
    
  • 实际上,原生js中,bind 底层用的就是 apply

  • bind是返回一个新函数,不执行

  • call和apply是会立刻执行的

call 函数实现

Function.prototype.customCall = function (context: any, ...args: any[]) {
  if (!context) context = globalThis
  if (typeof context !== 'object') context = new Object(context) // 值类型转化为对象
  const fnKey = Symbol()
  context[fnKey] = this // this 就是当前的函数
  const res = context[fnKey](...args) // 绑定了this 这是立即执行
  delete context[fnKey]
  return res
}

function fn(this:any, a:any, b:any, c:any) {
  console.log(this, a, b, c)
}

fn.customCall({x:100}, 1, 2, 3) // 这里会立即执行

apply 函数实现

Function.prototype.customApply = function (context: any, args: any[] = []) {
  if (!context) context = globalThis
  if (typeof context !== 'object') context = new Object(context) // 值类型转化为对象
  const fnKey = Symbol()
  context[fnKey] = this // this 就是当前的函数
  const res = context[fnKey](...args) // 绑定了this 这是立即执行
  delete context[fnKey]
  return res
}

function fn(this:any, a:any, b:any, c:any) {
  console.log(this, a, b, c)
}

fn.customApply({x:100}, 1, 2, 3) // 这里会立即执行

总结

  • 绑定 this
  • 传入执行参数
  • 分析:
    • 如何在函数执行时,绑定this
    • 如:const obj = {x: 100, fn() {this.x}}
    • 执行obj.fn(), 此时fn内部的this就指向obj
    • 可以借次来实现函数绑定 this
  • 用 call 实现 apply, 用 apply 实现 call 不可取
  • 原生 call apply 的 this
    • 如果this是值类型,会被 new Object(…)
    • 如果this是null的话,会变成 globalThis
  • Symbol 的作用,是防止属性之间的冲突
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Wang's Blog

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值