Skip to content

Instantly share code, notes, and snippets.

@AllanJunLi
Last active August 29, 2015 14:27
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 AllanJunLi/1e1b181c1e77c6d58b70 to your computer and use it in GitHub Desktop.
Save AllanJunLi/1e1b181c1e77c6d58b70 to your computer and use it in GitHub Desktop.
JS function closure
function greeter(saluatation) {
var counter = 0; // If in java counter needs to be defined as final
var prefix = '. ' + saluatation + ' ';
return function (name) { // is bound to counter and prefix, (we call the variables that we are bound to closure)
counter++; // same reference to the outter counter, therefore keeps state
return counter + prefix + name + '!';
};
}
var greet = greeter('Hello');
greet('World'); // 1. Hello World!
greet('World'); // 2. Hello World!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment