Eloquent Javascript: 高阶函数

Eloquent Javascript: Higher Order Functions

我正在浏览 Eloquent Javascript:下面的高阶函数示例并且已经阅读了问题和答案 here and 。但是我还是很迷茫。

function noisy(f) {
  return function(arg) {
    console.log("calling with", arg);
    var val = f(arg);
    console.log("called with", arg, "- got", val);
    return val;
  };
}
noisy(Boolean)(0);
// → calling with 0
// → called with 0 - got false
  1. noisy()只接受一个参数,即(Boolean),怎么能把(0)传给noisy(f)呢?我可以看到内部函数 f(arg) 基本上是 Boolean(0),但我不明白如何将两个参数传递给只允许一个参数的函数。 "noisy(Boolean)(0)(1)(2)(3);" 会是一个有效的函数调用吗?如果是这样,您将如何区分嘈杂函数中布尔值之后的每个值? "arg" 将引用哪个值?

  2. 书中指出示例函数正在修改另一个函数。修改的是哪个函数?我不明白作者 "modified".

  3. 的意思

but I don't understand how two parameters can get passed into a function that only allow one parameter

noisy returns一个函数,Boolean传递给noisy0传递给从[=11=返回的匿名函数],其中 fBooleanval 变为 Boolean(0)

例如

function fn1(arg1) {
  return function fn2(arg2) {
    console.log(arg1, arg2)
  }
}

// Call fn1, inside fn1 fn2 is called with `"b"` as parameter.
fn1("a")("b") // `a b`, `fn2` 

这是 JavaScript 中 currying 的概念,您可以在其中将函数柯里化为 return 部分应用的函数或传入其他函数

How can (0) be passed into noisy(f) since noisy() only takes one parameter and that is (Boolean)?

这个问题的答案是柯里化函数 noisy(),它需要一个函数 f 作为参数,而 return 是另一个函数。 returned 函数在 noisy 上有一个 闭包 ,因此它可以识别 Boolean 作为参数传递给 noisy即使在 returned 之后。这就是为什么调用 noisy(Boolean)(0) 基本上替代了 f=Boolean, arg=0

有关 currying 的更多信息,请参阅此内容:http://javascript.crockford.com/www_svendtofte_com/code/curried_javascript/ and closures: https://developer.mozilla.org/en/docs/Web/JavaScript/Closures