Created
February 5, 2013 21:22
-
-
Save tmcw/4717778 to your computer and use it in GitHub Desktop.
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
// quick demo of the technique of using | |
// closures to fix value references for functions | |
// that rely on loop variables that change. | |
var littleprinters = []; | |
for (var i = 0; i < 10; i++) { | |
littleprinters.push(function() { | |
return i; | |
}); | |
} | |
// pwned! | |
littleprinters[5](); | |
var littleclosures = []; | |
for (var i = 0; i < 10; i++) { | |
littleclosures.push((function(i) { | |
return function() { | |
return i; | |
}; | |
})(i)); | |
} | |
// success! | |
littleclosures[5](); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment