前端开发攻略---手写bind函数,看这篇就够了。

1、演示

2、bind函数介绍

在JavaScript中,bind() 函数用于创建一个新函数,其 this 关键字设置为提供的值,而不是调用时绑定的值。这对于在事件处理程序中绑定函数的上下文或者在类中绑定方法的上下文非常有用。

bind() 方法的语法如下:

function.bind(thisArg[, arg1[, arg2[, ...]]])

其中:

  • thisArg:绑定函数运行时 this 关键字所引用的对象。
  • arg1, arg2, ...:绑定函数运行时传递给原始函数的参数。

下面是一个示例,演示了如何使用 bind() 函数:

const person = {
  firstName: 'John',
  lastName: 'Doe',
  fullName: function() {
    return this.firstName + ' ' + this.lastName;
  }
};

const printName = person.fullName.bind(person);
console.log(printName()); // 输出 "John Doe"

在这个例子中,printName 函数绑定到了 person 对象上,所以它在调用时会输出正确的姓名。

bind() 函数不会立即调用原始函数,而是返回一个新函数,可以稍后调用。新函数的 this 值已经被绑定到了指定的对象。

3、手写bind函数

 

 <script>
    function fn(a, b, c, d) {
      console.log('fn called')
      console.log('args', a, b, c, d)
      console.log('this', this)
      return 123
    }
    Function.prototype.myBind = function (ctx, ...args) {
      const fn = this
      return function (...subArgs) {
        const allArgs = [...args, ...subArgs]
        if (new.target) {
          return new fn(...allArgs)
        } else {
          return fn.apply(ctx, allArgs)
        }
      }
    }
    const newFn = fn.myBind('ctx', 1, 2)
    console.log(newFn(3, 4))
  </script>

这段代码定义了一个自定义的 myBind 方法,用于模拟原生的 bind 方法。让我们逐行解释:

  1. function fn(a, b, c, d) { ... }: 这是一个普通的 JavaScript 函数,它接受四个参数并在调用时打印相关信息。

  2. Function.prototype.myBind = function (ctx, ...args) { ... }: 这里扩展了 Function 的原型,添加了一个名为 myBind 的方法。这个方法接受一个上下文 ctx 和一系列参数 args

  3. const fn = this: 将调用 myBind 的函数保存在 fn 变量中。

  4. return function (...subArgs) { ... }: 返回一个函数,这个函数接受任意数量的参数 subArgs

  5. const allArgs = [...args, ...subArgs]: 将 myBind 方法传入的参数 args 和返回函数接受的参数 subArgs 合并成一个新数组 allArgs

  6. if (new.target) { ... } else { ... }: 这里使用 new.target 来检查函数是通过 new 关键字调用的还是普通函数调用。如果是通过 new 调用的,则使用 new fn(...allArgs) 创建一个新的实例并返回。如果是普通函数调用,则使用 fn.apply(ctx, allArgs) 在指定上下文 ctx 下调用函数。

最后,使用 myBind 方法创建了一个新的函数 newFn,并传入了一个上下文 'ctx' 和两个初始参数 1 和 2。当调用 newFn(3, 4) 时,传入的参数 3 和 4 会被传递给原始函数 fn,以及之前绑定的参数 1 和 2,然后原始函数会在指定的上下文中执行。

  • 3
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

bbamx.

谢谢您

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

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

打赏作者

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

抵扣说明:

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

余额充值