JavaScript:为什么只有在将return函数赋给变量时才会发生闭包? [英] JavaScript: Why does closure only happen if I assign the return function to a variable?
问题描述
即使在阅读您不了解JS 和 JavaScript:核心我仍然无法理解以下代码的行为。
Even after reading You don't know JS and JavaScript: The Core I still couldn't understand the behavior of the following code.
为什么,当我调用 counter()()
时,我是否会收到闭包,但如果我指定一个变量到 counter()
的结果,就像 var getClosure = counter()
,然后在调用<时得到一个闭包code> getClosure()?
Why, when I call counter()()
, do I get no closure, but if I assign a variable to the result of counter()
, like var getClosure = counter()
, I then get a closure when calling getClosure()
?
function counter() {
var _counter = 0;
function increase() { return _counter++ }
return increase;
}
// Double ()() to call the returned function always return 0, so no closure.
counter()() // returns 0
counter()() // returns 0
counter()() // returns 0
counter()() // returns 0
var createClosure = counter();
createClosure() // returns 0
createClosure() // returns 1
createClosure() // returns 2
createClosure() // returns 3
推荐答案
_counter
是函数 counter()
中的局部变量。每次拨打 counter()
时,都会创建一个新的 _counter
。
_counter
is the local variable within function counter()
. Every time when you call counter()
a new _counter
will be created.
但 var createClosure = counter()
仅调用函数1次,这就是为什么 _counter
是不是每次都新创造并且记住那里(这就是关闭发生的地方)
But var createClosure = counter()
only called the function 1 time, that's why _counter
is not newly created every time and 'remembered' there (that's where closure happens)
这篇关于JavaScript:为什么只有在将return函数赋给变量时才会发生闭包?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!