aplicar () método llama a una función de un valor dado de este parámetro como una matriz (o matriz-como objetos) está provisto de, también.
Sintaxis: func.apply (thisArg, [argsArray])
aplicar (), y call () es similar excepto que la llamada () que recibe una lista de parámetros, y aplicar () recibe una matriz de parámetros, se consigue un simple cambio en la llamada () de podemos mirar en el formulario de referencia
Function.prototype.myApply = function(thisArg, args) {
if(typeof this !== 'function') {
throw new TypeError('error')
}
const fn = Symbol('fn') // 声明一个独有的Symbol属性, 防止fn覆盖已有属性
thisArg = thisArg || window // 若没有传入this, 默认绑定window对象
thisArg[fn] = this // this指向调用call的对象,即我们要改变this指向的函数
const result = thisArg[fn](...args) // 执行当前函数
delete thisArg[fn] // 删除我们声明的fn属性
return result // 返回函数执行结果
}
//测试
foo.myApply(obj, []) // 输出'写代码像蔡徐抻'
En este artículo se reimprime de: https://juejin.im/post/5e8b261ae51d4546c0382ab4