Created
October 24, 2012 14:09
-
-
Save szydan/3946251 to your computer and use it in GitHub Desktop.
Avoiding the Reference Problem inside loops
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
// borrowed from jsvascript garden | |
// http://bonsaiden.github.com/JavaScript-Garden/#function.closures | |
// In order to copy the value of the loop's index variable, it is best to use an anonymous wrapper | |
for(var i = 0; i < 10; i++) { | |
(function(e) { | |
setTimeout(function() { | |
console.log(e); | |
}, 1000); | |
})(i); | |
} | |
// The anonymous outer function gets called immediately with i as its | |
// first argument and will receive a copy | |
// of the value of i as its parameter e. | |
// The anonymous function that gets passed to setTimeout now has a reference to e, whose value does not get // changed by the loop. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment