Created
November 29, 2012 18:43
-
-
Save easierbycode/4171043 to your computer and use it in GitHub Desktop.
emulate block scope
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
// 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