call、apply和bind的简单实现

本文详细介绍了JavaScript中call、apply和bind三个方法的作用及其实现方式。call和apply用于立即调用函数并改变其this指向,而bind则创建一个新的函数,并设置其this上下文。文中还提供了这三个方法的简易实现代码。

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

call、apply 和 bind

  • call 和 apply: 会调用原来的函数并改变其 this 的指向,this指向的是传递过来的第一个参数
  • bind:返回一个新的函数,在新的函数内部会调用用原来的函数;并改变其 this 的指向,this 为传递的第一个参数
  • call、apply、bind 的第一个参数若为 null 或 undefined 的话,那么 this 的指向将变为 window
  • call 和 apply 的区别就是传递的参数不同
    • call可以接受多个参数
    • apply 只能传入两个参数,第二个参数
      往往是数组

call 的简单实现

Function.prototype.myCall = function (context, ...args) {
  //  防止与函数发生命名冲突的问题,以至于覆盖原来的函数
  let fn = Symbol('fn');
  // 处理 context 为 null 或 undefined 的问题
  const ctx = context || window;
  ctx[fn] = this;
  const result = ctx[fn](...args);
  delete ctx[fn];
  return result;
}

apply 的简单实现

apply 和 call 很相似,只是在处理参数的方便略有不同

Function.prototype.myApply = function (context, args = []) {
  let fn = Symbol('fn');
  const ctx = context || window;
  ctx[fn] = this;
  const result = ctx[fn](...args);
  delete ctx[fn];
  return result;
}

bind 的简单实现

Function.prototype.myBind = function (context, ...arg1) {
  return (...arg2) => {
    const fn = Symbol('fn');
    const ctx = context || window;
    ctx[fn] = this;
    const result = ctx[fn](...arg1, ...arg2);
    delete ctx[fn];
    return result;
  }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值