简体   繁体   中英

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?

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));
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM