ChickenDreamFactory / fe-chicken

✨✨✨ 集锦 前端JavaScript 手写题,编程题,Not just for interviews

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

50.apply

webVueBlog opened this issue · comments

// 为函数绑定执行上下文
// 原理:将函数设置为执行上下文的一个方法,然后调用执行上下文的方法
// ctx 指定的函数执行上下文
// args 剩余参数组成的数组
// any 返回函数的执行结果
Function.prototype.myApply = function (ctx, args) {
 // fn.myApply(ctx, [arg1, arg2])
 // this 是正在执行的函数
 const fn = this
 // 保证 ctx[key] 的唯一性,避免和用户设置的 context[key] 冲突
 const key = Symbol()
 // 将执行函数 设置 到指定的上下文对象上
 ctx[key] = fn
 // 执行函数
 const res = ctx[key](...args)
 // 删除上下文的 fn 方法
 delete ctx[key]
 // 返回函数的执行结果
 return res
}