Created
January 26, 2011 22:11
-
-
Save rtgibbons/797592 to your computer and use it in GitHub Desktop.
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
function makeCounter() { | |
// `i` is only accessible inside the closure created when the | |
// `makeCounter` function is invoked. | |
var i = 0; | |
return function() { | |
console.log( ++i ); | |
}; | |
} | |
// Note that `counter` and `counter2` each have their own scoped `i`, | |
// because the closure containing `i` is created when the function | |
// `makeCounter` is invoked. | |
var counter = makeCounter(); | |
counter(); // logs: 1 | |
counter(); // logs: 2 | |
var counter2 = makeCounter(); | |
counter2(); // logs: 1 | |
counter2(); // logs: 2 | |
i; // ReferenceError: i is not defined (it only exists inside the closures) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment