apply实现

Function.prototype.myApply = function(obj, arr) { //记忆:该应用(apply)帮天霸(判)执单(删)反(返)
  let context = Object(obj) || globalThis; //1.绑定全局环境     绑
  context.fn = this; //2.添加临时属性存储调用函数                 添
  if(!Array.isArray(arr)) { //3.判断传入参数是否为数组            判
    throw new SyntaxError(`${arr} is not an array`)
  }

  let result = context.fn(...arr)//4.执行函数                  执

  delete context.fn //5.删除临时属性                            删

  return result //6.返回执行结果                                返

}

let arr = [1, 2, 3];
let obj = {name: 123}

function add(...a) {
  console.log(this)
  console.log(`args: ${a}`)
}

add.myApply({}, arr)
add.myApply(obj, arr)
posted @ 2022-10-29 16:52  我喝牛奶不舔盖  阅读(32)  评论(0)    收藏  举报
I hear and I forget. I see and I remember. I do and I understand