admin管理员组文章数量:1394165
In the code below please can someone explain to me why multiple calls to counter
result in the value of i
increasing each time it is called?
My understanding is that as we specifically set i = 0;
in makeCounter
, each time makeCounter
is called through the counter
variable, i
should be reset to 0. I cannot understand why this is not the case.
function makeCounter() {
// `i` is only accessible inside `makeCounter`.
var i = 0;
return function() {
console.log( ++i );
};
}
// Note that `counter` and `counter2` each have their own scoped `i`.
var counter = makeCounter();
counter(); // logs: 1
counter(); // logs: 2
In the code below please can someone explain to me why multiple calls to counter
result in the value of i
increasing each time it is called?
My understanding is that as we specifically set i = 0;
in makeCounter
, each time makeCounter
is called through the counter
variable, i
should be reset to 0. I cannot understand why this is not the case.
function makeCounter() {
// `i` is only accessible inside `makeCounter`.
var i = 0;
return function() {
console.log( ++i );
};
}
// Note that `counter` and `counter2` each have their own scoped `i`.
var counter = makeCounter();
counter(); // logs: 1
counter(); // logs: 2
Share
Improve this question
edited Jul 1, 2013 at 14:34
Ian
50.9k13 gold badges104 silver badges111 bronze badges
asked Jul 1, 2013 at 14:27
BenMBenM
4,2682 gold badges33 silver badges58 bronze badges
2 Answers
Reset to default 10each time makeCounter is called through the "counter" variable
That is wrong.
You're only calling makeCounter()
once – at var counter = makeCounter();
.
counter
is a reference to the returned function, which closes over the i
variable.
Calling counter()
will execute this returned function, just like any other function.
The behavior you're expecting would happen if you write makeCounter()()
multiple times.
each time makeCounter is called […]
i
should be reset to0
That's right.
makeCounter
is called through thecounter
variable
No it's not. The anonymous function returned by makeCounter
is called with counter()
. makeCounter
was only called once, its result was assigned to the counter
variable.
Note that
counter
andcounter2
each have their own scopedi
That would be the case, yes. However your example is inplete:
var counter = makeCounter();
counter(); // logs 1
var counter2 = makeCounter();
counter2(); // logs 1 again!
counter(); // still logs 2
counter2(); // logs 2
本文标签:
版权声明:本文标题:Why do javascript variables in closure functions not reset to a default when called multiple times? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744085741a2588485.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论