Tuesday, May 8, 2012

ColdFusion Closures By Zeus


ColdFusion 10 introduced a new feature called ‘ColdFusion Closures’.
A closure is an inner function. The inner function can access the variables in the outer function. You can access the inner function by accessing the outer function. See the example below.
function helloTranslator(String helloWord)
{
return function(String name) {
return “#helloWord#, #name#”;
};
}
helloInEnglish=helloTranslator(“Hello”);
helloInFrench=helloTranslator(“Bonjour”);
writeoutput(helloInEnglish (“Arindam”));
//closure is formed.
//Prints Hello, Arindam.
writeoutput(“<br>”);
writeoutput(helloInFrench(“Arindam”));
//Prints Bonjour, Arindam.
In the above example, the outer function returns a closure.
Using the helloInEnglish variable, the outer function is accessed. It sets the helloWord argument.
Using this function pointer, the closure is called. For example, helloInEnglish (“Arindam “).
Observe that even after the execution of outer function, the closure can access the variable sets by the outer function.
In this case, using closure, two new functions are created. One adds Hello to the name. And the second one adds Bonjour to the name.
helloInEnglish and helloInFrench are closures. Though they have the same function body they store different environments.
The inner function is available for execution after the outer function is returned.
A closure is formed when the inner function is available for execution. As seen in the example, even after the outer function is returned, the inner function can access the variables in the outer function.
Closure retains the reference to the environment at the time it is created. For example, the value of a local variable in the outer function. It makes closure an easy to use and handy feature.
Source: help.adobe.com/en_US/ColdFusion/10.0/Developing/index.html
Article written : Arindam Roy