何时在回调函数中使用括号? ES6风格

时间:2018-08-14 20:48:42

标签: javascript ecmascript-6 callback functional-programming

const billerBuilder = (stateName) => {
  const innerBuilder = (customShipping, customTax) => {
    return (itemPrice) => (itemPrice * customShipping * customTax);
  }
  const nyShipping = 1.03;
  const nyTax = 1.04;
  const njShipping = 1.05;
  const njTax = 1.06625;
  switch (stateName) {
    case 'NY':
      return innerBuilder(nyTax, nyShipping);
    case 'NJ':
      return innerBuilder(njTax, njShipping);
    default:
      return itemPrice;
  }
}
let newYorkBiller = biller('NY');
newYorkBiller(100);

为什么没有带有3个参数的innerBuilder是返回给billerBuilder的参数?为什么带有参数itemPrice的未命名函数变成了newYorkBiller。

如果itemPrice是一个未命名的函数,当我尝试命名它时,代码为什么不起作用?

1 个答案:

答案 0 :(得分:0)

如果要命名,则应将其存储在const中并返回const。

const innerBuilder = (customShipping, customTax) => {
    const namedFunc = (itemPrice) => (itemPrice * customShipping * customTax);
    return namedFunc;
  }

但是我不明白您为什么要命名。如果是我,我将其更改为:

const innerBuilder = (customShipping, customTax) => (itemPrice) => (itemPrice * customShipping * customTax);

此技术称为currying

https://medium.com/@kbrainwave/currying-in-javascript-ce6da2d324fe