为什么这个闭包函数没有编译器错误?

Why no compiler error for this closure function?

我正在阅读 Marijn Haverbeke 的优秀著作“Eloquent JavaScript”。 https://eloquentjavascript.net/

我不理解 this example 没有定义 number 的闭包,但没有错误。

number是函数还是参数?

没有任何迹象表明第二次传入number作为参数

function multiplier(factor) {
  return number => number * factor;
}

let twice = multiplier(2);
console.log(twice(5));
// → 10

了解闭包的工作原理已经够难了,但是当您正在查看的示例任意混合函数声明和 arrow function - 就像这个一样 - 如果您不了解箭头函数的工作原理更难理解。

这是一个稍微简单的示例,它不使用箭头函数来显示正在发生的事情。

// `multipler` takes a factor as an argument
function multiplier(factor) {

  // It returns a function that - when it's called -
  // accepts a number
  return function (number) {

    // And the return from that function
    // is the factor * number
    return number * factor;
  }
}

// So we call `multipler` with a factor and assign the
// function it returns to our `twice` variable
let twice = multiplier(2);

// We can then call the function assigned
// to `twice` with a number, and the resulting
// return from that function will be factor * number
console.log(twice(5));

就使用该箭头函数的示例而言:

// We pass in a factor to the `multipler`
function multiplier(factor) {
  
  // We return a function that accepts a number
  // and returns factor * number
  // (I've added parentheses around the number
  // parameter to clearly show it)
  return (number) => number * factor;
}

// So we call `multipler` with a factor and assign the
// function it returns to our `twice` variable
let twice = multiplier(2);

// We can then call the function assigned
// to `twice` with a number, and the resulting
// return from that function will be factor * number
console.log(twice(5));