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 @   我喝牛奶不舔盖  阅读(22)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 字符编码:从基础到乱码解决
· 提示词工程——AI应用必不可少的技术
I hear and I forget. I see and I remember. I do and I understand
点击右上角即可分享
微信分享提示