Estaba jugando con esta matriz reduce polyfill y estoy confundido por qué está usando apply . Sé que apply agrega this contexto en la ejecución. Pero no sé por qué lo necesitamos aquí, lo intenté sin él y también funciona bien.
Array.prototype.reduce = function (cb, initialValue) { console.log('inside my reducer'); if (!cb || typeof cb !== 'function') throw TypeError(); var len = this.length; var i = 0; console.log('this', this); if (typeof initialValue === 'undefined' || initialValue === null) { initialValue = this[0]; ++i; } for (; i < len; i++) { initialValue = cb.apply(this, [initialValue, this[i], i, this]); //comment the line above and uncomment this line and it will work fine //initialValue = cb(initialValue, this[i]); } return initialValue; }; [1, 2, 1, 1].reduce((a, b) => a + b, 0); => 5Entonces, estoy un poco confundido, si alguien pudiera compartir algunas ideas, sería apreciado. ¡Gracias!
Dondequiera que haya obtenido ese polyfill, es incorrecto, en un par de formas, pero en particular que initialValue = cb.apply(this, [initialValue, this[i], i, this]); debería estar usando undefined , no this , en el primer argumento. reduce siempre llama a su devolución de llamada con this conjunto en undefined (terminará siendo el objeto global si la devolución de llamada está en modo suelto en lugar de modo estricto). Así que initialValue = cb.apply(undefined, [initialValue, this[i], i, this]); o (más directamente) initialValue = cb(initialValue, this[i], i, this);
Por separado, no tiene sentido usar apply y crear una matriz para proporcionarle en lugar de usar call con los valores discretos que ya tiene. Además, continuar usando algo llamado initialValue para el acumulador es, en el mejor de los casos, engañoso. Y no lo maneja correctamente si haces [].reduce(x => x) (debería arrojar un error, no devolver undefined [nota sin valor inicial]).
Básicamente, no pondría mucha fe en ese polyfill, ya que proporciona la matriz, en lugar de undefined , como this durante las devoluciones de llamada.