手撕call、apply、bind

65 阅读1分钟
  1. call
Function.prototype.Mycall = function(target, ...args) {
  target = target || window
  const symbolKey = Symbol()
  target[symbolKey] = this
  const res = target[symbolKey](...args)
  delete target[symbolKey]
  return res
}
  1. apply
Function.prototype.Myapply = function(target, args) {
  target = target || window
  const symbolKey = Symbol()
  target[symbolKey] = this
  const res = target[symbolKey](...args)
  delete target[symbolKey]
  return res
}
  1. bind
Function.prototype.Mybind = function(target, ...outArgs) {
  target = target || {}
  const symbolKey = Symbol()
  target[symbolKey] = this
  return function(...innerArgs) {
    const res = target[symbolKey](...outArgs, ...innerArgs)
    return res
  }
}