Skip to content

Instantly share code, notes, and snippets.

@rtgibbons
Created January 26, 2011 22: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 rtgibbons/797592 to your computer and use it in GitHub Desktop.
Save rtgibbons/797592 to your computer and use it in GitHub Desktop.
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