function makeAddFunction(amount) {
function add(number) {
return number + amount;
}
return add;
}
var addTwo = makeAddFunction(2);
var addFive = makeAddFunction(5);
show(addTwo(1) + addFive(1));
答案 0 :(得分:2)
makeAddFunction()
是一个返回新创建的函数的函数。结果取决于传递给amount
的{{1}}参数。
makeAddFunction()
当您编写function makeAddFunction(amount) {
function add(number) {/*
We define a function add() that takes 1 argument
return number + amount;//The function returns our "number" argument
plus some "amount", determined by what's passed to makeAddFunction().
At this stage, you can think of "amount" as a fixed number.
*/
}
return add;//We return the add() function, which takes the "number" argument
}
var addTwo = makeAddFunction(2);/*We create a function that takes "number" and
returns "number" + 2. The returned function is exactly the same as:
function(number){return number + 2;}
*/
var addFive = makeAddFunction(5);/*We create a function that takes "number" and
returns "number" + 5. The returned function is exactly the same as:
function(number){return number + 2;)
*/
show(addTwo(1) + addFive(1));//The result is (1 + 2) + (1 + 5) = 9
时,解释程序会记住给定上下文中makeAddFunction(5)
的内容,因此生成的函数等效于:
amount