Created
December 11, 2012 21:26
-
-
Save thomasballinger/4262261 to your computer and use it in GitHub Desktop.
Javascript Closures
This file contains hidden or 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
// 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