Last active
August 29, 2015 14:27
-
-
Save AllanJunLi/1e1b181c1e77c6d58b70 to your computer and use it in GitHub Desktop.
JS function closure
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 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