有人可以向我解释此JavaScript函数的流程吗? (关闭概念) [英] Can someone explain me the flow of this JavaScript function? (Closure concept)
问题描述
我正在阅读 出色的JavaScript 。第3章介绍了 关闭的概念,并提供了一些示例。其中一个是下一个:
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
我想我理解这个概念。如果首先我执行 console.log(两次)
,由于变量 number
未定义,我得到的是 [功能]
。我不了解两次(5)
的工作方式。为什么局部变量 number
初始化为值 5
?
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
?
此外,为什么我执行 console.log(multiplier(2,5))
我也不会结果是10?
Also, why if I execute console.log(multiplier(2,5))
I don't get 10 as a result?
谢谢。
推荐答案
由于乘数
返回一个函数,因此两次
等于返回的函数,而不是乘数
函数。
Because multiplier
returns a function, so twice
is equal to the returned function, NOT the multiplier
function.
但是,当调用乘数
时,会在返回的函数中传递并使用 factor
变量。
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;
};
其中 factor
已被替换为值您在调用乘数(2)
时失败了。
Where factor
has been replaced by the value you passed in when calling multiplier(2)
.
我想我理解这个概念。如果首先我执行
console.log(两次)
,由于变量号未定义,我得到的是[Function]
I think I understood the concept. If first I execute
console.log(twice)
, since variable number is undefined, what I get is[Function]
.
当您使用 console.log(两次)
时,您实际上并不是调用函数两次
,您只是在记录它的值。所以 [Function]
的输出不是因为 number
是未定义的,而是因为您正在输出实际的函数,而不是
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.
此外,为什么我执行
console.log(multiplier(2,5))
结果没有得到10?
在这里,您通过提供2个参数来调用乘数
,尽管您仅定义了接受一个参数( factor
)。在javascript中,这不会导致错误,但是您只会在 factor
( factor = 2
)。
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)
可能会得到 10
可能感兴趣的是使用以下代码:
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
这篇关于有人可以向我解释此JavaScript函数的流程吗? (关闭概念)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!