[英]Why does this closure example work incorrect?
I've seen examples of closure and I thought I understand them, until I decided to do this:我看过闭包的例子,我以为我理解它们,直到我决定这样做:
var f = [];
for (var i = 0; i < 2; i++) {
f[i] = function foo(a) {
var h = i;
function bar() {
console.log(h);
}
if (a == 1)
bar();
}
}
for (var j = 0; j < 2; j++) {
console.log(f[j](1));
}
The output is this:输出是这样的:
2
2
When I thought it would be 0, 1
since I created an outer function foo
where I store i
in the variable h
Can someone explain what happens here and why those setTimeout
examples work correct?当我认为它是
0, 1
因为我创建了一个外部函数foo
,我将i
存储在变量h
有人可以解释这里发生了什么以及为什么那些setTimeout
示例工作正常吗?
For the desired output update your code to following对于所需的输出更新您的代码如下
var f = [];
for (var i = 0; i < 2; i++) {
f[i] = (function(i){
return function foo(a) {
var h = i;
function bar() {
console.log(h);
}
if (a == 1)
bar();
}
})(i);
}
for (var j = 0; j < 2; j++) {
console.log(f[j](1));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.