Skip to content

Instantly share code, notes, and snippets.

@mosijava
Created July 27, 2018 12:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mosijava/2067fd364e85164999943ca48e12f1d2 to your computer and use it in GitHub Desktop.
Save mosijava/2067fd364e85164999943ca48e12f1d2 to your computer and use it in GitHub Desktop.
a way to solve classic closure problem in javascript
var myFunctions= [];
function createMyFunction(i) {
return function() {
console.log("My value: " + i);
};
}
for (var i = 0; i < 3; i++) {
myFunctions[i] = createMyFunction(i);
}
for (var j = 0; j < 3; j++) {
myFunctions[j](); // and now let's run each one to see
}
*/
My value: 0
My value: 1
My value: 2
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment