Skip to content

Instantly share code, notes, and snippets.

@tmcw
Created February 5, 2013 21:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tmcw/4717778 to your computer and use it in GitHub Desktop.
Save tmcw/4717778 to your computer and use it in GitHub Desktop.
// 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