Created
December 13, 2015 08:25
-
-
Save parambirs/2e3e2c36c51a9e8835f5 to your computer and use it in GitHub Desktop.
Closure - problem and solution
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
var result = []; | |
for (var i=0; i < 5; i++) { | |
result.push(function () { return i }); // (1) | |
} | |
console.log(result[1]()); // 5 (not 1) | |
console.log(result[3]()); // 5 (not 3) | |
for (var i=0; i < 5; i++) { | |
(function () { | |
var i2 = i; // copy current i | |
result.push(function () { return i2 }); | |
}()); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment