手写 apply 方法 超级详细 ⚡⚡⚡

582 阅读2分钟

本文已参与「新人创作礼」活动,一起开启掘金创作之路。

大家好我是CoderBin

1. 函数作用

调用函数,可传入参数(数组),改变this指向

2. 总体步骤

  1. 边界判断(this, context, argArray)
  2. 将调用的函数设置为对象(传入的context)的方法(改变this指向)
  3. 调用函数,得到返回值,并返回

3. 详细步骤

1. 边界判断

  • 判断当前 this 是否为一个函数,否则返回错误消息
  • 判断是否传入 context 参数,存在则使用 Object() 转换为对象赋给 context,否则将 window 赋值给 context
  • 判断 是否传入argArray,没传等赋值为空数组

2. 将调用的函数设置为对象(传入的context)的方法(改变this指向)

3. 调用函数,得到返回值,并返回

  • 调用函数,得到结果
  • 删除 context 身上的 fn 函数
  • 返回结果

4. 代码实现

/**
 * !实现 binApply() 方法
 * @param {*} context 绑定的对象
 * @param  {...any} argArray 数组
 * @returns 
 */
 Function.prototype.binApply = function(context, argArray) {
  if (typeof this !== 'function') return console.error('Error')
  context = (context!==null && context!==undefined) ? Object(context) : window
  argArray = argArray || []

  context.fn = this
  
  const result = context.fn(...argArray)
  delete context.fn
  return result
}

5. 测试代码

// 测试
function sum(num1, num2) {
  console.log('sum 被执行', this);
  return num1 + num2
}

// 原生的 apply() 方法
console.log(sum.apply({name: 'bin'}, [1,2]));

// 自定义的 binApply() 方法
console.log(sum.binApply({name: 'bin'}, [1,2]));

6. 细节解析

  1. apply() 方法的第二个参数是数组
  2. this 指向的就是调用 binApply() 的那个函数(隐式绑定);
  3. 传入的 context 参数表示:将 this 的指向改为这个参数;
  4. 改变 this 指向其实就是在 context 上添加一个临时的方法,值为 this
  5. 调用 context.fn() 时,就已经改变了 this 的指向,同时得使用展开运算符传入参数
  6. delete context.fn 删除那个临时方法是因为已经不需要用了

7. 核心原理

通过在传入的对象上,临时新增一个方法,这个方法的值是当前 binApply 的调用者。然后 context.fn(...argArray) 调用这个函数,通过隐式绑定的方式改变了 this 的指向,最后得到结果并返回


每文一句:古今来许多世家,无非积德。天地间第一人品,还是读书。

本次的分享就到这里,希望大家都能够有所收获。有任何疑问都可以在评论区留言,大家一起探讨、进步!