手写call函数(原理讲解)

打电话

实现call

Function.prototype.myCall = function(context) {
  // 如果不传入第一个参数,那么「上下文」默认为 window
  if(typeof context === undefined || typeof context === null) {
    context = window
  }
  const symbol = Symbol()
  context[symbol] = this
  const args = [...arguments].slice(1)
  const result = context[symbol](...args)
  delete context[symbol]
  return result
}

顺便说一下apply

其实apply的实现也是类似的,区别只是参数的处理上不一样:

Function.prototype.myApply = function(context) {
  if(typeof context === undefined || typeof context === null) {
    context = window
  }
  const symbol = Symbol()
  context[symbol] = this
  let result
  // 处理参数和 call 有区别
  if(arguments[1]) {
    result = context[symbol](...arguments[1])
  } else {
    result = context[symbol]()
  }
  delete context[symbol]
  return result
}