lexical scoping in javascript
I'm reading this book: http://eloquentjavascript.net/ which I think is brilliant.
However I'm having difficulty understanding the following function, where does the function add(number) get its argument from?
function makeAddFunction(amount) {
function add(number) {
return nu开发者_运维技巧mber + amount;
}
return add;
}
var addTwo = makeAddFunction(2);
var addFive = makeAddFunction(5);
show(addTwo(1) + addFive(1)); // gives 9
I thought the answer would be 7 to this show(addTwo(1) + addFive(1));
In makeAddFunction(2)
, amount is 2, but what would number be? so number + 2...
NB: show function is pretty much echo in php.
makeAddFunction
returns a new function. The new function takes a param, number
, and adds it to whatever was originally given to makeAddFunction
.
var addTwo = makeAddFunction(2);
// addTwo is now a function which you can call with a numeric argument ('number')
// anything you pass to it will have two added to it
var five = addTwo( 3 ); // add two to three (makes five)
See JAAulde's answer for what makeAddFunction
's purpose is, which was really the main question, imo
The answer to your second question is, you generate two functions. They look like this (basically):
var addTwo = function add(number) {
return number + 2;
};
var addFive = function add(number) {
return number + 5;
};
It should be obvious why you get:
addTwo(1) + addFive(1)
(1 + 2)
+ (1 + 5)
= 9 now.
What would number be? Number is an argument to the returned function. I think you're thinking about this too hard.
makeAddFunction(5)
effectively returns a named reference to function(number) { return number + 5; }
精彩评论