尝试手写call/apply/bind

88 阅读1分钟

call

Function.prototype._call = function (context, ...args) {
  const obj = context == undefined ? window : Object(context)

  const key = Symbol()

  obj[key] = this

  const result = obj[key](...args)

  delete obj[key]

  return result
}

apply

Function.prototype._apply = function (context, ...args) {
  const obj = context == undefined ? window : Object(context)

  const key = Symbol()

  obj[key] = this

  const result = obj[key](...args)

  delete obj[key]

  return result
}

bind

Function.prototype._bind = function (context, ...args) {
  const self = this

  const newFn = function (...rest) {
    return self.call(context, ...args, ...rest)
  }

  if (self.prototype) {
    self.prototype = Object.create(self.prototype)
  }

  return newFn
}