所以我是编程新手,我正尝试通过Eloquent Javascript学习JS。
到目前为止一切都很好,直到我得到了以下代码的示例
function makeAddFunction(amount) {
function add(number) {
return number + amount;
}
return add;
}
var addTwo = makeAddFunction(2);
var addFive = makeAddFunction(5);
show(addTwo(1) + addFive(1));
注意:show就像是警报,只在教程已集成的JS控制台的屏幕上显示变量。
作者说,这是一个示例,展示了词法作用域如何允许综合功能。
Chapter here
我不明白的是
addTwo
和addFive
(应该是变量)如何将参数发送到函数makeAddFunction
和add
,更具体地说,函数add
如何知道变量正在发送的参数是参数number
。感谢您的帮助!
最佳答案
我认为理解该示例的关键是理解函数可以返回其他函数(就像其他任何变量一样)。记录该代码将有助于理解该概念。
/**
* Creates an adder function
* @param {number} amount Amount to add
* @return {function} Method that adds 'amount' to its argument.
* See the documentation of add for its signature
*/
function makeAddFunction(amount) {
/**
* Everytime makeAddFunction is called, a new instance of add is created
* (and returned) that holds on to its copy of 'amount' (through the closure)
* @param {number} number value to add to 'amount'
* @return {number} 'amount' + 'number'
*/
return function add(number) {
return number + amount;
};
}
// addTwo now is a reference to a function that when called
// adds 2 to whatever is passed in
var addTwo = makeAddFunction(2);
// addFive Adds 5 to its argument
var addFive = makeAddFunction(5);
// addTwo(1) = 3, addFive(1) = 6, therefore, output is 9
show(addTwo(1) + addFive(1));