Skip to content

Instantly share code, notes, and snippets.

@thomasballinger
Created December 11, 2012 21:26
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thomasballinger/4262261 to your computer and use it in GitHub Desktop.
Save thomasballinger/4262261 to your computer and use it in GitHub Desktop.
Javascript Closures
// Closures are sometimes unintuitive!
console.log('the smart way');
funs = []
for (var a = 0; a < 3; a++){
funs.push(function(){
var newa = a;
return function(){console.log(newa);}
}())
}
for (var i = 0; i < 3; i++){
funs[i]();
}
console.log('the naive way');
funs = [];
(function(){ // the function block for scope doesn't help at all here, it's just to
// say that this doesn't help
for (var a = 0; a < 3; a++){
funs.push(function(){console.log(a);});
}
})();
for (var i = 0; i < 3; i++){
funs[i]();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment