Last active
October 6, 2015 20:38
-
-
Save itod/3050315 to your computer and use it in GitHub Desktop.
JavaScript Closure
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function foo() { | |
var res = []; | |
for (var i = 0; i < 3; i++) { | |
res.push(function() { | |
document.write(i); | |
}); | |
} | |
return res; | |
} | |
var funcs = foo(); | |
for (var i = 0; i < funcs.length; i++) { | |
funcs[i](); | |
} | |
// prints: | |
// 333 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I don't have clear explanation. Just, that 'var i' in for loop is bind to foo() and i in function(){...document.write(i)} is evaluated at the last value of i of the for loop.
By removing var in for loop it works as expected
... for (i = 0; i < 3; i++) { ....
But it makes i 'global scope' ...so like this, is it really still a closure ? Don't know... Javascript quirk ?