call实现

Function.prototype.myCall = function(obj) {  //靠(call),帮(绑)甜(添)姐(解)执单(删)反(返)
  let context = obj || window; //1.绑定全局环境             绑
  context.fn = this; //2.添加临时属性存储调用函数             添
  let args = [...arguments].slice(1) //3.解析参数          解
  let result = context.fn(...args); //4.执行函数,取得结果   执
  delete context.fn; //5.删除临时属性                       删
  return result //6.返回执行结果                            返
}

let obj = {
  name: 'xx'
};

function showName(...args) {
  console.log(`name: ${this.name}, args: ${args}`)
}

showName.myCall(obj,34, 35, 36)
posted @ 2022-10-29 16:58  我喝牛奶不舔盖  阅读(82)  评论(0)    收藏  举报
I hear and I forget. I see and I remember. I do and I understand