Skip to content

手写apply、call、bind

MyCall的实现

js
Function.prototype.MyCall = function(ctx, ...args) {
  if (typeof this !== 'function') {
    throw new Error('被调用的对象必须是函数')
  }
  const fn = Symbol('key')
  ctx[fn] = this
  const result = ctx[fn](...args)
  delete ctx[fn]
  return result
}

MyApply的实现

js
Function.prototype.MyApply = function(ctx, args = []) {
  if (typeof this !== 'function') {
    throw new Error('被调用的对象必须是函数')
  }
  if (!Array.isArray(args)) {
    throw new Error('第二个参数必须是数据')
  }
  const fn = Symbol('key')
  ctx[fn] = this
  const result = fn(...args)
  delete ctx[fn]
  return result
}

MyBind的实现

js
Function.prototype.MyBind = function(ctx, ...args) {
  if (typeof this !== 'function') {
    throw new Error('被调用的对象必须是函数')
  }
  const fn = this
  return function (...innerArgs) {
    if (new.target) {
      return new fn(...args,...innerArgs)
    }
    return fn.MyApply(ctx, [...args,...innerArgs])
  }
}

备案号:豫ICP备17017964号