JavaScript: 多个参数

JavaScript: Multiple arguments

举例说明如何在 JavaScript 中使用 "currying":

const component = (argument1) => (argument2) => {
   // Do something
}

您的代码包含两个嵌套箭头函数的简短版本。这是完整版的样子(使用 return 语句和括号应该看起来更清楚):

let component = (argument1) => { 
   // console.log(argument1);
   return (argument2) => {
       // console.log(argument2);
   }
}

component('aa')('bb');

第一个函数(带参数 1)return 函数。 returned 函数接受参数 2。

在您的代码中有两个箭头函数,一个 returns 另一个可以帮助您使用 Closure state/scope 维护

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures

const multiplier = (argument1) => (argument2) => {
   return argument2 * argument1;
};

const multiples8 = multiplier(8);

console.log(multiples8(5));
console.log(multiples8(6));
console.log(multiples8(7));

你所做的就是链接。

const add = (a) => (b) => {
    return a + b;
}

var add5 = add(5); // returns partially applied function
var result = add5(4); // which can be invoked with its own parameter

console.log(result); // 9

箭头函数提供了更清晰的语法,因为如果只有一个参数,您可以省略参数周围的括号,如果函数体是单行,您可以省略方括号。我们可以使用常规的 js 函数语法编写相同的代码:

const add = function(a){
    return function(b){
    return a + b
  }
}

这就是所谓的函数柯里化。它对于实现装饰器模式等很有用。

例如,假设我们从一个简单的函数开始 add

const add = (a, b) => a + b;

console.log(add(1, 2));

现在,假设我们要将两个数字相加,但每次都要相加十。

我们可以这样做:

const add = (a, b) => a + b + 10;

console.log(add(1, 2));

但是,我们失去了原来的功能。

所以我们使用函数柯里化来做这两件事:

// We keep the original add function
const add = (a, b) => a + b;

// And create another function that returns the modified function
const addTen = (addFunction) => (a, b) => 10 + addFunction(a, b);

// then we store the new function in a different variable
const addPlusTen = addTen(add);

// ...and call the returned function

console.log(add(1, 2));
console.log(addPlusTen(1, 2));

// This becomes useful when we need to make an addPlusFive, addPlusSix and addPlusSeven functions:

const addFive = (addFunction) => (a, b) => 5 + addFunction(a, b);
const addSix = (addFunction) => (a, b) => 6 + addFunction(a, b);
const addSeven = (addFunction) => (a, b) => 7 + addFunction(a, b);

const addPlusFive = addFive(add);
const addPlusSix = addSix(add);
const addPlusSeven = addSeven(add);

console.log(addPlusFive(1, 2));
console.log(addPlusSix(1, 2));
console.log(addPlusSeven(1, 2));