在 Eloquent JavaScript 中,作者提供了以下示例 + 散文:
With a slight change, we can turn the previous example into a way to create functions that multiply by an arbitrary amount.
function multiplier(factor) {
return function(number) {
return number * factor;
};
}
var twice = multiplier(2);
console.log(twice(5));
// → 10 The explicit
localVariable from the wrapValue example isn’t needed since a parameter is itself a local variable.
Thinking about programs like this takes some practice. A good mental model is to think of the function keyword as “freezing” the code in its body and wrapping it into a package (the function value). So when you read return function(...) {...}, think of it as returning a handle to a piece of computation, frozen for later use.
In the example, multiplier returns a frozen chunk of code that gets stored in the twice variable. The last line then calls the value in this variable, causing the frozen code (return number * factor;) to be activated. It still has access to the factor variable from the multiplier call that created it, and in addition it gets access to the argument passed when unfreezing it, 5, through its number parameter.
javascript 如何知道 5 在:
console.log(twice(5));
应该是数字的值? JavaScript 本质上是在自言自语“我已经有了 2 作为 factor 的值,我不能改变它,所以 5 必须是 number 的值”。
换句话说
var twice = multiplier(2)
so twice = multiplier(2) {return function (number)}
thus twice(5) = multiplier(2) {return function (5)}
这样对吗?
如果 multiplier 中有另一个局部变量,我可以调用:
twice(5,10)
javascript 会知道这意味着:
factor = 2
number = 5
third variable = 10
最佳答案
ES6 版本
const multiplier = factor => {
return number => number * factor;
}
让我感到困惑的部分是认为变量“两次”被分配了乘数函数,而不是乘数函数(也是一个函数)的return。
const twice = multiplier(2);
所以实际分配的是:
const twice = number => number * 2
twice(2)
-> 10
关于javascript - Eloquent javascript - 闭包和函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34208916/