JavaScript示例问题:词法作用域/关闭-雄辩的Javascript [英] JavaScript example question: lexical scoping/closure - Eloquent Javascript
问题描述
所以我是编程新手,我正尝试通过Eloquent Javascript一书来学习JS.
So I'm new to programming and I'm trying to learn JS with the book Eloquent Javascript.
到目前为止,一切都很好,直到我得到了下面的代码示例
So far so good, until I reached an example with the following code
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控制台的屏幕上显示变量.
note: show is like alert, only it shows the variables on the screen of a JS console the tutorial has integrated.
作者说,这是一个示例,展示了词法作用域如何允许综合功能. 此处
The author says this is an example to show how lexical scoping allows to synthesise functions. Chapter here
我不了解的是addTwo
和addFive
(应该是变量)如何将参数发送到函数makeAddFunction
和add
,更具体地说,函数add
如何知道变量发送的参数是参数number
.
What I don't understand is how addTwo
and addFive
, which supposedly are variables, can send parameters to the functions makeAddFunction
and add
, and more specifically, how does the function add
knows that the parameter the variables are sending is the parameter number
.
感谢您的帮助!
推荐答案
我认为理解示例的关键是理解函数可以返回其他函数(就像其他任何变量一样).记录该代码将有助于理解该概念.
I think the key to understanding that example is understanding that functions can return other functions (just like any other variable). Documenting that code will go a long way in helping understand that concept.
/**
* 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));
这篇关于JavaScript示例问题:词法作用域/关闭-雄辩的Javascript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!