(十六) apply()方法及其实现

1. apply()方法

apply()方法与call()方法用法完全一致, 唯一的区别就是参数的不同

function.apply(thisArg, arrayArgs)

  • thisArg: 在 function 函数运行时使用的 this
  • arrayArgs: 是一个参数数组

示例

var obj = {
  name: '猫',
  age: 13,
}

function showInfo(num1, num2) {
  console.log('我的个人信息是: ', this.name + this.age);

  return num1 + num2
}

var total = showInfo.apply(obj, [10, 20])		// 我的个人信息是:  猫13

console.log(total);		// 30

2. 利用原生js模拟apply()方法

前面利用原生js实现了call()方法, 而apply()与call唯一的区别就是第二个参数的不同

因此, 实现思路是完全一致的, 只需要稍微改动一下对参数的处理即可

实现如下:

Function.prototype.myApply = function (context, arrArgs) {
  if (typeof context !== 'object') {
    context = Object.create(null)
  } else {
    context = context || window
  }

  let res

  context.fn = this
  res = context.fn(...arrArgs)
  delete context.fn

  return res
}

测试

var obj = {
  name: '猫',
  age: 13,
}

function showInfo(num1, num2) {
  console.log('我的个人信息是: ', this.name + this.age);

  return num1 + num2
}

var total = showInfo.myApply(obj, [10, 20])		// 我的个人信息是:  猫13

console.log(total);		// 30
posted @ 2021-07-29 21:19  只猫  阅读(361)  评论(0编辑  收藏  举报