实现一个 call,apply和bind

79 阅读1分钟

call

使用方式: fn.call(context, arg1, arg2, arg3)

 Function.prototype.customCall = function (context, ...params) {
  context = context || window
  context.fn = this
  const ret = context.fn(...params)
  delete context.fn
  return ret
}

apply

使用方式: fn.apply(context, [arg1, arg2, arg3])

Function.prototype.customApply = function (context, params) {
  context = context || window
  context.fn = this
  let ret
  if (params) {
    ret = context.fn(...params)
  } else {
    ret = context.fn()
  }
  delete context.fn
  return ret
}

bind

使用方式: fn.bind(context, arg1, arg2, arg3) 因为 bind 是返回一个 函数, 所以 可以new

Function.prototype.customBind = function (obj, ...args) {
  const parent = this
  function retFn (...params) {
    const ret = parent.apply(obj, [...params, ...args])
    if (typeof ret === 'object') return ret
  }
  retFn.prototype = Object.create(parent.prototype)
  Object.defineProperty(retFn.prototype, 'constructor', {
    value: retFn,
    enumerable: false,
    writable: false,
    configurable: false
  })
  return retFn
}