Entiendo cómo funciona esto, pero no puedo entender por qué queremos usar apply con la palabra clave "this" como en el ejemplo a continuación:
function curry(func) { return function curried(...args) { if (args.length >= func.length) { return func.apply(this, args) } else { return curried.bind(this, ...args) } } }Aquí vincular y aplicar usa "esto" como primer argumento, pero ¿cuál es el propósito si solo podemos hacer func (args) ya que esto apunta al mismo entorno léxico de una función? Puedo ver algunos beneficios con funciones de flecha, pero aquí he nombrado funciones. ¿No hay diferencia o me estoy perdiendo algo?
La razón para usar apply es mantener el mismo valor de this . Llamar a func(args) daría como resultado que this sea el objeto de la window (en modo no estricto) o undefined (en modo estricto).
Aquí hay un ejemplo que se rompe si llamas a func(args) :
function curry(func) { return function curried(...args) { if (args.length >= func.length) { return func(args); } else { return curried.bind(this, ...args); } }; } const example = { multiplier: 5, calculate: function (a, b) { return (a + b) * this.multiplier; }, }; example.curriedVersion = curry(example.calculate); // Because of the way these are being called, `this` should be `example` console.log(example.calculate(1, 2)); // But here it's not, causing unexpected results console.log(example.curriedVersion(1)(2)); Pero funciona si apply(this, args) :
function curry(func) { return function curried(...args) { if (args.length >= func.length) { return func.apply(this, args); } else { return curried.bind(this, ...args); } }; } const example = { multiplier: 5, calculate: function (a, b) { return (a + b) * this.multiplier; }, }; example.curriedVersion = curry(example.calculate); // Because of the way these are being called, `this` should be `example` console.log(example.calculate(1, 2)); console.log(example.curriedVersion(1)(2));