Function.prototype.apply 实现原理

1,914 阅读1分钟

Function.prototype.apply

方法说明

apply方法的作用和call方法一样,不同之处在于提供参数的方式,apply使用参数数组,而call使用一组参数列表

源码关键点在于

同Function.prototype.call方法的实现一致,还是要在传递进来的上下文对象中构建一个需要执行的方法

源码

Function.prototype.myApply = function (ctx, args) {
  ctx = ctx || window
  const fn = Symbol()
  ctx[fn] = this
  const res = ctx[fn](...args)
  delete ctx[fn]
  return res
}

// 示例代码
function test (arg1, arg2) {
  return `${this.name}, ${arg1} ${arg2}`
}
const obj = {
  name: 'I am obj'
}
const res = test.myApply(obj, ['hello', 'world !!'])
console.log(res)  // I am obj, hello world !!