JavaScript function or expression that binds variables internally to their value when the function was spawned.
Useful to limit context for callback function, settimeout loops, or other situations where you want to maintain variables privacy between requests or function callbacks.
Example:
var person = function () {
var name = “Robert”;
return {
getName : function () {
return name;
},
setName : function (newName) {
name = newName;
}
};
}(); //Having parenthesis () runs the function as it is defined
alert(person.name); // Undefined
alert(person.getName()); // Robert
person.setName(“Robert Nyman”);
alert(person.getName()); // “Robert Nyman”
Another example:
function addLinks () {
for (var onclick = function(num){return function(){alert(num)}}, i=0, link; i<5; i++) {
link = document.createElement(”a”);
link.innerHTML = “Link ” + i; Append links that onclick will produce an alert with the original ‘I’ variable assigned to it
link.onclick = onclick(i);
document.body.appendChild(link);
}
};
onload = addLinks;
Another example:
function callLater(paramA, paramB, paramC){ /* Return a reference to an anonymous inner function created with a function expression:- */
return (function(){ /* This inner function is to be executed with – setTimeout – and when it is executed it can read, and act upon, the parameters passed to the outer function:- */
paramA[paramB] = paramC; });
} … /* Call the function that will return a reference to the inner function object created in its execution context. Passing the parameters that the inner function will use when it is eventually executed as arguments to the outer function. The returned reference to the inner function object is assigned to a local variable:- */
var functRef = callLater(elStyle, “display”, “none”); /* Call the setTimeout function, passing the reference to the inner function assigned to the – functRef – variable as the first argument:- */
hideMenu=setTimeout(functRef, 500);
keyword: closures