Skip to content

Instantly share code, notes, and snippets.

@rsliter
Created December 3, 2012 16:58
Show Gist options
  • Select an option

  • Save rsliter/45ba3ef454d9696d2bb5 to your computer and use it in GitHub Desktop.

Select an option

Save rsliter/45ba3ef454d9696d2bb5 to your computer and use it in GitHub Desktop.
Closures in JavaScript
/*
Allows you to declare functions within functions.
The functions are expressed rather than declared, as in the myClosure function expression below:
*/
function myFunction() {
var myClosure = function() { alert hello;};
return myClosure;
}
/*
What's really tricky about this is that the anonymous functions that are being passed around
don't execute until they are called. Thus, variables that have been set outside of the
anonymous function can be accessed, but they will always be the final assigned value.
*/
function myFunction(anArray) {
var closures = [];
for(var i1 = 0; i1 < anArray.length; i1++){
var myClosure = function() { alert("Value: " + i1);};
closures.push(myClosure);
}
return closures;
}
/*
Note that myFunction returns a collection of functions. These functions have not yet been executed--
in fact, they can be passed around to be executed later. In order to execute the closures returned by
myFunction, the call would look like this:
*/
var closures = myFunction([1,2,3]);
for (var i2 = 0; i2 < closures.length; i2++) {
closures[i]();
}
/*
Because i1 was incremented before the closure actually executed, the following text
will be alerted three times:
*/
"Value: 3"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment