手写 apply call bind

// 手写 apply
Function.prototype.newApply = function (context, args) {
  // 判断 this 是否为函数
  if (typeof this !== 'function') {
    throw new TypeError('Not a Function')
  }
  // 判断传入参数是否为空
  context = context || window
  args = args ? args : []
  // 为 context 增添属性 fn
  context.fn = this
  // 通过隐式绑定调用函数
  const result = context.fn(...args)
  // 删除添加的属性
  delete context.fn
  return result
}

// 手写 call
Function.prototype.newCall = function (context, ...args) {
  if (typeof this !== 'function') {
    throw new TypeError('Not a Function')
  }
  context = context || window
  args = args ? args : []
  context.fn = this
  const result = context.fn(...args)
  delete context.fn
  return result
}

// 手写 bind
Function.prototype.newBind = function (context, ...args) {
  if (typeof this !== 'function') {
    throw new TypeError('Not a Function')
  }
  args = args ? args : []
  const fn = this
  return function newFn(...newFnArgs) {
    if (this instanceof newFn) {
      return new fn(...args, ...newFnArgs)
    }
    return fn.apply(context, [...args, ...newFnArgs])
  }
}
笔记
  • call、apply、bind 三者区别
fn.call(obj, 1, 2); // fn立即执行
fn.bind(obj, 1, 2); // fn不执行
fn.apply(obj, [1, 2]);
  • this 绑定的四种方式
  1. 默认绑定:作用于函数直接调用的情况下,此时this指向全局对象,但严格模式下this指向

  2. 隐式绑定:this指向它的调用者,即谁调用函数,他就指向谁

  3. 显式绑定:通过call、apply或bind实现

  4. new绑定:
    使用new操作符时实际做了四件事:
    ① 创建一个全新的对象
    ② 执行原型链接,使新对象的__proto__指向原函数的prototype
    ③ 这个新对象会被绑定到构造函数中的this
    ④ 执行构造函数,判断返回值,如果为对象,则返回这个值,否则返回默认创建的对象

    优先级:new > 显式 > 隐式 > 默认。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值