问题
I'm reading "Eloquent JavaScript". Chapter 3 introduces "Closure" concept and gives you a couple of examples. One of these is next one:
function multiplier(factor) {
return function(number) {
return number * factor;
};
}
var twice = multiplier(2);
console.log(twice(5));
// → 10
I think I understood the concept. If first I execute console.log(twice)
, since variable number
is undefined, what I get is [Function]
. What I don't understand is how twice(5)
works. Why local variable number
is initialized with value 5
?
Also, why if I execute console.log(multiplier(2,5))
I don't get 10 as a result?
Thanks.
回答1:
Because multiplier
returns a function, so twice
is equal to the returned function, NOT the multiplier
function.
However, when multiplier
is called the factor
variable is passed and used within the returned function.
So to make it easier to understand, consider that twice
is basically:
var twice = function(number) {
return number * 2;
};
Where factor
has been replaced by the value you passed in when calling multiplier(2)
.
I think I understood the concept. If first I execute
console.log(twice)
, since variable number is undefined, what I get is[Function]
.
When you use console.log(twice)
you are not actually calling the function twice
, you are simply logging the value of it. So the output of [Function]
is not because number
is undefined, it is because you are outputting the actual function rather than the result of it.
Also, why if I execute
console.log(multiplier(2,5))
I don't get 10 as a result?
Here you are calling the multiplier
by providing 2 arguments, though you have only defined the function to accept one parameter (factor
). In javascript, this won't cause an error, but you will just get the first value mapped in factor
(factor = 2
).
Note: There are ways to still access all the supplied arguments even if you don't have parameters defined for them (here's an example)
Something that would be possible to get a result of 10
which might be of interest is to use the following code:
var result = multiplier(2)(5); // result = 10
回答2:
multiplier is a function which returns anonymous function which accepts an argument(number)
var twice = multiplier(2);
Basically is :-
var twice = function(number) {
return number * 2;
};
回答3:
If you execute
console.log(multiplier(2,5))
you call the function giving two parameters, whereas
function multiplier(factor) {}
only takes one parameter.
来源:https://stackoverflow.com/questions/38739810/can-someone-explain-me-the-flow-of-this-javascript-function-closure-concept