A friend of mine and I are currently discussing what is a closure in JS and what isn't.
(我的一个朋友和我正在讨论什么是JS的封闭,什么不是。)
We just want to make sure we really understand it correctly.(我们只是想确保我们真正理解它。)
Let's take this example.
(我们来看看这个例子吧。)
We have a counting loop and want to print the counter variable on the console delayed.(我们有一个计数循环,并希望在控制台上打印计数器变量延迟。)
Therefore we usesetTimeout
and closures to capture the value of the counter variable to make sure that it will not print N times the value N.(因此,我们使用setTimeout
和闭包来捕获计数器变量的值,以确保它不会打印N倍N值。)
The wrong solution without closures or anything near to closures would be:
(错误的解决方案,而闭合或接近闭合 ,以将任何东西:)
for(var i = 0; i < 10; i++) {
setTimeout(function() {
console.log(i);
}, 1000);
}
which will of course print 10 times the value of i
after the loop, namely 10.
(这将当然打印的10倍的值i
在循环后,也就是10。)
So his attempt was:
(所以他的尝试是:)
for(var i = 0; i < 10; i++) {
(function(){
var i2 = i;
setTimeout(function(){
console.log(i2);
}, 1000)
})();
}
printing 0 to 9 as expected.
(按预期打印0到9。)
I told him that he isn't using a closure to capture i
, but he insists that he is.
(我告诉他,他并没有使用封闭来捕获i
,但他坚持认为他是。)
setTimeout
(passing his anonymous function to setTimeout
), printing 10 times 10 again.(我通过将for循环体放在另一个setTimeout
(将他的匿名函数传递给setTimeout
),再次打印10次10??来证明他没有使用闭包 。)
var
and execute it after the loop, also printing 10 times 10. So my argument is that he doesn't really capture the value of i
, making his version not a closure.(如果我将他的函数存储在var
并在循环之后执行它同样适用,也打印10次10??.所以我的论点是他并没有真正捕获 i
的值 ,使他的版本不是一个闭包。)
My attempt was:
(我的尝试是:)
for(var i = 0; i < 10; i++) {
setTimeout((function(i2){
return function() {
console.log(i2);
}
})(i), 1000);
}
So I capture i
(named i2
within the closure), but now I return another function and pass this around.
(所以我捕获了i
(在闭包中命名为i2
),但现在我返回另一个函数并传递它。)
i
.(在我的例子中,传递给setTimeout的函数实际上捕获了i
。)
Now who is using closures and who isn't?
(现在谁在使用闭包,谁不是?)
Note that both solutions print 0 to 9 on the console delayed, so they solve the original problem, but we want to understand which of those two solutions uses closures to accomplish this.
(请注意,两个解决方案在控制台上打印0到9都会延迟,因此它们解决了原始问题,但我们想要了解这两个解决方案中的哪一个使用闭包来实现此目的。)
ask by leemes translate from so