Skip to content

Instantly share code, notes, and snippets.

@easierbycode
Created November 29, 2012 18:43
Show Gist options
  • Save easierbycode/4171043 to your computer and use it in GitHub Desktop.
Save easierbycode/4171043 to your computer and use it in GitHub Desktop.
emulate block scope
// http://bit.ly/gettingclosure
for (var i = 1; i <= 3; i++) {
(function(i){
// All variables (including i)
// are now scoped to this block
// On click, alerts '1', '2' and '3'
$elem.click(function() { alert(i); });
})(i);
}
// another way
function makeAlert(i) {
return function() {
alert(i)
}
}
for (var i = 1; i <= 3; i++) {
// On click, alerts '1', '2' and '3' :D
$elem.click(makeAlert(i));
}
// otherwise, i is shared by all functions created in this loop.
for (var i = 1; i <= 3; i++) {
// On click, alerts '4', '4' and '4' :(
$elem.click(function() { alert(i); });
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment