大厂面试题 手写实现call函数

86 阅读1分钟

手写实现call函数


var person={
  getName(a,b){
    console.log('getName:::this',this)
    return this.name
  }
}
const man={
  name:'奶茶不加冰七分甜'
}

Function.prototype.myCall=function(content){
  
  if(typeof this!=='function'){
    throw new Error('this is not a function')
  }
  
  const arr=[...arguments].slice(1)
  
  content.fn= this //该this是getName函数
  
  const res=content.fn(...arr) //该this是getName函数
  
  delete content.fn
  
  return res
}

const res=person.getName.myCall(man,'奶茶只喝常温','666')