<p>
Closures are means through which inner functions can refer to the variables present in their outer enclosing function after their parent functions have already terminated.
</p>
<pre data-sub="prettyprint:_">
function delayedAlert(msg, time)
{
setTimeout(function(){
alert(msg);
}, time);
}
delayedAlert("Welcom!", 2000);
</pre>
<p>
Curring is a way to to, essentially, prefill in a number of arguments to a function, creating a new, simpler function. Closure can create such currying functionality.
</p>
<pre data-sub="prettyprint:_">
function addGenerator(num)
{
//return a simple function for adding two
//numbers with first number barrowed from the generator
return function(toAdd){
return number + toAdd
};
}
var addFive = addGenerator(5);
add(addFive(4) == 9);
</pre>
<p>
There's another, common, javascript coding problem that closures can solve. New javascript developers tend to accidentally leave a lot of extra variable sitting in the global scope. This is generally considered to be bad practice, as those extra variable could quietly interfere with other libraries, causing confusing problem to occur. Using a self-executing, anonymous function you can essentially hide all normally globally variables from being seen by other code.
</p>
<pre data-sub="prettyprint:_">
(function(){
//The variable that would, normally, be global
var msg = "Thanks for visiting!";
//binding a new function to a global object
window.onunload = function(){
alert(msg)
};
})(); //close off the anonymous function and execute it
</pre>
<p>
Remember that closures allow you to reference variables that exist within the parent function. However, it does not provide the value of the variable at the time it is created. It provides the last value of the variable with in the parent function. The most common issue under which you'ill see this occur is during a for loop. This is one variable being
</p>
<pre data-sub="prettyprint:_">
// An element with an ID of main
var obj = document.getElementById("main");
// An array of items to bind to
var items = [ "click", "keypress" ];
// Iterate through each of the items
for ( var i = 0; i < items.length; i++ )
{
// Use a self-executed anonymous function to induce scope
(
function()
{
// Remember the value within this scope
var item = items[i];
// Bind a function to the elment
obj[ "on" + item ] = function() {
// item refers to a parent variable that has been successfully
// scoped within the context of this for loop
alert( "Thanks for your " + item );};
}
)();
}
</pre>