Last active
August 29, 2015 14:15
-
-
Save tatocaster/9dab2948de03247c7726 to your computer and use it in GitHub Desktop.
js scopes in for loop
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
/** | |
* given expression | |
*/ | |
var run = function(){ | |
var arr = []; | |
for(var i = 0; i<=10; i++){ | |
arr.push(function(){ | |
alert(i); | |
}); | |
} | |
for(var j = 0; j<=10; j++){ | |
arr[j](); | |
} | |
} | |
run(); | |
/* solution*/ | |
var run = function(){ | |
var arr = []; | |
for(var i = 0; i<=10; i++){ | |
arr.push( | |
(function(k) { | |
/* immediately invoked function pattern */ | |
return function() { | |
alert(k); | |
}; | |
})(i) | |
); | |
} | |
for(var j = 0; j<=10; j++){ | |
arr[j](); | |
} | |
} | |
run(); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment