手写call和apply

43 阅读1分钟

// call Function.prototype.myCall = function(context){ // 判读当前this是否为函数 if(typeof this !== 'function'){ throw Error('error') } // 第一个参数如果传值则为第一个参数,如果不传则为window context = context || window // 在目标对象身上临时定义一个方法,来接收this context.fn = this // 把函数的参数值从二位截取下来 let args = [...arguments].slice(1) // 把截取的参数传入函数中得出结果 let res = context.fn(...args) delete context.fn return res } console.log(person.getName.myCall(person1))

// apply
Function.prototype.myApply = function(context){
  if(typeof this !== 'function'){
    throw Error('error')
  }
  context = context || window
  context.fn = this
  let res
  // 如果参数又第二项
  if(arguments[1]){
    res = context.fn([...arguments[1]])
  }else{
    res = context.fn()
  }
  delete context.fn
  return res
}