-
-
Save rsliter/45ba3ef454d9696d2bb5 to your computer and use it in GitHub Desktop.
Closures in JavaScript
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
| /* | |
| 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