模拟实现apply
Function.prototype._apply = function (targetObject, argsArray) { // 若是没有传递,则置为空数组 if(typeof argsArray === 'undefined' || argsArray === null) { argsArray = [] } // 是否传入执行上下文,若没有指定,则指向 window if(typeof targetObject === 'undefined' || targetObject === null){ targetObject = window } // 利用Symbol的特性,设置为key const targetFnKey = Symbol('key') // 将调用_apply的函数赋值 targetObject[targetFnKey] = this // 执行函数,并在删除之后返回 const result = targetObject[targetFnKey](...argsArray) delete targetObject[targetFnKey] return result }
使用Symbol作为key,是为了防止重复,例如targetFnKey设置为cb,当传入的targetObject自身拥有cb这个方法,就会导致执行之后便呗delete,导致问题
转自:https://mp.weixin.qq.com/s/tIasEjYJRaVqFMN_aVtpiw