A simple example of a closure in Javascript. It demonstrates how the returned function maintains access to the variables defined in the function that defined the returned function (is this an infinite loop description).
function closure__get_display_name_logger(name)
{
var display_name = "User: " + name;
var display_name_logger = function log_display_name()
{
console.log(display_name);
}
//function returns a function
return display_name_logger;
}
//save returned function
var display_name_logger = closure__get_display_name_logger("Homer");
//use returned function
//the display name variable is maintained, "closed" within the function
display_name_logger();
//this will return a function and the the returned function will always have access to the counter variable
function closure__get_counter_logger()
{
var counter = 0;
var counter_logger = function log_counter()
{
counter++;
console.log(counter);
}
return counter_logger;
}
//function returns a function
var counter_logger = closure__get_counter_logger();
//use returned function
//the returned function still has access to the counter variable
counter_logger(); //1
counter_logger(); //2
counter_logger(); //3
counter_logger(); //4
counter_logger(); //5