Skip to content

Instantly share code, notes, and snippets.

@andrewdavey
Created September 13, 2010 15:50
Show Gist options
  • Save andrewdavey/577496 to your computer and use it in GitHub Desktop.
Save andrewdavey/577496 to your computer and use it in GitHub Desktop.
// This won't work as you probably want
for (var i = 0; i < 10; i++) {
handlers.push(function() {
use(i);
});
}
// This won't work due to "var yanking"
for (var i = 0; i < 10; i++) {
var j = i;
handlers.push(function() {
use(j);
});
}
// This will capture the value of i correctly.
for (var i = 0; i < 10; i++) {
(function(j) {
handlers.push(function() {
use(j);
});
})(i);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment