手写 bind 函数

bind 函数通过传入一个对象,返回一个 this 指向传入对象的新函数。这个函数的 this 指向除了使用 new 时会被改变,其他情况下都不会改变。

Function.prototype.myBind = function (ctx, ...args) {
  // 判断调用对象是否为函数
  if (typeof this !== 'function') {
    throw new TypeError(`${this}.myBind is not a function`);
  }
  // 保存当前函数的引用
  const fn = this;
  return function Fn(...restArgs) {
    if (this instanceof Fn) { // 或使用 new.target 判断是否通过 new 调用
      return new fn(...args, ...restArgs);
    }
    return fn.apply(ctx, [...args, ...restArgs]);
  };
};

测试:

function fn(a, b, c) {
  console.log('fn called');
  console.log(`arguments:`, a, b, c);
  console.log('this:', this);
  return 'result';
}

const newFn = fn.myBind('ctx', 1);
console.log(newFn(2, 3));
// 输出结果:
// fn called
// arguments: 1 2 3
// this: [String: 'ctx']
// result

console.log(new newFn(2, 3));
// 输出结果:
// fn called
// arguments: 1 2 3
// this: fn {}
// fn {}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值