For the complete experience, please enable JavaScript in your browser. Thank you!

  • Creative Cloud
  • Photoshop
  • Illustrator
  • InDesign
  • Premiere Pro
  • After Effects
  • Lightroom
  • See all
  • See plans for: businesses photographers students
  • Document Cloud
  • Acrobat DC
  • eSign
  • Stock
  • Elements
  • Marketing Cloud
  • Analytics
  • Audience Manager
  • Campaign
  • Experience Manager
  • Media Optimizer
  • Target
  • See all
  • Acrobat Reader DC
  • Adobe Flash Player
  • Adobe AIR
  • Adobe Shockwave Player
  • All products
  • Creative Cloud
  • Individuals
  • Photographers
  • Students and Teachers
  • Business
  • Schools and Universities
  • Marketing Cloud
  • Document Cloud
  • Stock
  • Elements
  • All products
  • Get Support
    Find answers quickly. Contact us if you need to.
    Start now >
  • Learn the apps
    Get started or learn new ways to work.
    Learn now >
  • Ask the community
    Post questions and get answers from experts.
    Start now >
    • About Us
    • Careers At Adobe
    • Investor Relations
    • Privacy  |  Security
    • Corporate Responsibility
    • Customer Showcase
    • Events
    • Contact Us
News
    • 3/22/2016
      Adobe Summit 2016: Are You An Experience Business?
    • 3/22/2016
      Adobe Announces Cross-Device Co-op to Enable People-Based Marketing
    • 3/22/2016
      Adobe and comScore Advance Digital TV and Ad Measurement
    • 3/22/2016
      Adobe Marketing Cloud Redefines TV Experience
Developing Applications Help / 

Using closures

Adobe Community Help


Applies to

  • ColdFusion

Contact support

 
By clicking Submit, you accept the Adobe Terms of Use.
 

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#";
};
}
helloInHindi=helloTranslator("Namaste");
helloInFrench=helloTranslator("Bonjour");
writeoutput(helloInHindi("Anna"));
//closure is formed.
//Prints Namaste, Anna.
writeoutput("<br>");
writeoutput(helloInFrench("John"));
//Prints Bonjour, John.
</cfscript>

In the above example, the outer function returns a closure. Using the helloHindi variable, the outer function is accessed. It sets the helloWord argument. Using this function pointer, the closure is called. For example, helloInHindi("Anna"). 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 Namaste to the name. And the second one adds Bonjour to the name. helloInHindi and helloInFrench are closures. They have the same function body; however, 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.
To see more details on closure, see http://jibbering.com/faq/notes/closures.

Closure in ColdFusion

A closure can be of the following categories:

  • Defined inline without giving a name. They can be used in the following ways:
    • They can be assigned to a variable, array item, struct, and variable scope. It can be returned directly from a function. 

      Example

function operation(string operator)
{
return function(numeric x, numeric y)
{
if(operator eq "add")
{
return x + y;
}
else if(operator eq "subtract")
{
return x - y;
}
};
}
myval_addition=operation("add");
myval_substraction=operation("subtract");
writeoutput(myval_addition(10,20));
writeoutput("<br>");
writeoutput(myval_substraction(10,20));
</cfscript>

In the above example, the outer function sets the operator. myval_addition and myval_substraction are two closures. They process the data based on the condition sets by the outer function.

  • Defined inline as a function and tag argument.Example

function operation(numeric x, numeric y, function logic)
{
var result=logic(x,y);
return result;
}
add = operation(10,20, function(numeric N1, numeric N2)
{
return N1+N2;
});
subtract = operation(10,20, function(numeric N1, numeric N2)
{
return N1-N2;
});
</cfscript>
<cfdump var="#add#">
<cfdump var="#substract#">

In the above example, the function operation has an argument logic, which is a closure. While calling operation, an inline closure is passed as an argument. This anonymous closure contains the logic to process the numbers - addition or subtraction. In this case, the logic is dynamic and passed as a closure to the function.

A Closure can be assigned to a variable

You can assign a closure to a variable.
Example

var c2 = function () {..}

Note:

When assigning Closures to a variable, only script style of syntax is supported.

A closure can be used as a return type

You can use a closure as a return type.

Note:

As a best practice, if the return type is a closure, provide the Function keyword with initial capitalization.

Example

Function function exampleClosure(arg1) 
{ 
	function exampleReturned(innerArg) 
	{ 
		return innerArg + arg1; 
	} 
	/* 
	return a reference to the inner function defined. 
	*/ 
return exampleReturned; 
}
Calling closure with key-value pair

You can call a closure by passing a key-value pair as you do for a function call.
Example

var c2 = function(arg1, arg1) {..} 
c2(arg1=1, arg2=3);
Closure can be assigned to a variable outside function

You can assign a closure to a variable outside the function.
Example

hello = function (arg1) 
{ 
	writeoutput("Hello " & arg1); 
}; 
hello("Mark");
Calling closure with argument collection

Example

var c2 = function(arg1, arg1) {..} 
argsColl = structNew(); 
argsColl.arg1= 1; 
argsColl.arg2= 3; 
c2(argumentCollection = argsColl);

Closures and functions

A closure retains a copy of variables visible at the time of its creation. The global variables (like ColdFusion specific scopes) and the local variables (including declaring or outer function's local and arguments scope) are retained at the time of a closure creation. Functions are static.
The following table details the scope of closure based on the way they are defined:

Scenario where closure is defined

Scope

In a CFC function

Closure argument scope, enclosing function local scope and argument scope, this scope, variable scope, and super scope

In a CFM function

Closure argument scope, enclosing function local scope and argument scope, this scope, variable scope, and super scope

As function argument

Closure argument scope, variable scope, and this scope and super scope (if defined in CFC component).

In closure, following is the order of search for an unscoped variable:

  1. Closure's local scope
  2. Closure's arguments scope
  3. Outer function's local scope if available
  4. Owner function's local scope if available
  5. ColdFusion built-in scope

Note:

A closure cannot call any user-defined function, because the function's context is not retained, though the closure's context is retained. It gives erroneous results. For example, when a closure is cached, it can be properly called for later use, while a function cannot.

Closure functions

The following are the closure functions:

isClosure
Description

Determines whether a name represents a closure.

Returns

True, if name can be called as a closure; False, otherwise.

Category

Decision functions

Syntax
isClosure(closureName__)
See also

Other decision functions.

History

ColdFusion 10: Added this function.

Parameters

Parameter

Description

closureName

Name of a closure. Must not be in quotation marks.Results in an error if not a defined variable or function name.

Usage

Use this function to determine whether the name represents a closure.

Example
<cfscript> 
	isClosure(closureName) 
	{ 
	 // do something 
	} 
	else 
	{ 
	 // do something 
	} 
</cfscript>
Modifications to the function isCustomFunction

Though closure is a function object, it is not considered as a custom function.
The function now returns:

  • True: If name can be called as a custom function.
  • False: If name can be called as a closure.

Usage scenarios

The following scenario explains how you can effectively use ColdFusion closures.

Example - filtering of arrays using closures

The following example filters employees based on location, age, and designation. A single function is used for filtering. The filtering logic is provided to the function as closures. That's filtering logic changes dynamically.

Example
  1. Create the employee.cfcfile that defines the variables.

/** 
* @name employee 
* @displayname ColdFusion Closure Example 
* @output false 
* @accessors true 
*/ 
component 
{ 
property string Name; 
property numeric Age; 
property string designation; 
property string location; 
property string status; 
}
  1. Create the employee array. This CFC also contains the filterArray() }}function. A closure, {{filter, is an argument of the function. While accessing this function, the filtering logic is passed as a closure.
<!---filter.cfc---> 
<cfcomponent> 
<cfscript> 
//Filter the array based on the logic provided by the closure. 
function filterArray(Array a, function filter) 
	{ 
		resultarray = arraynew(1); 
			for(i=1;i<=ArrayLen(a);i++) 
			{ 
				if(filter(a[i])) 
				ArrayAppend(resultarray,a[i]); 
			} 
		return resultarray; 
	} 
function getEmployee() 
	{ 
//Create the employee array. 
	empArray = Arraynew(1); 
	ArrayAppend(empArray,new employee(Name="Ryan", Age=24, designation="Manager", location="US")); 
	ArrayAppend(empArray,new employee(Name="Ben", Age=34, designation="Sr Manager", 	location="US")); 
	ArrayAppend(empArray,new employee(Name="Den", Age=24, designation="Software Engineer", location="US")); 
	ArrayAppend(empArray,new employee(Name="Ran", Age=28, designation="Manager", location="IND")); 
	ArrayAppend(empArray,new employee(Name="Ramesh", Age=31, designation="Software Engineer", location="IND")); 
	return empArray; 
	} 
</cfscript> 
</cfcomponent>
  1. Create the CFM page that accesses the {{filterArray()}}function with a closure which provides the filtering logic. The {{filterArray()}}function is used to filter the employee data in three ways: location, age, and designation. Each time the function is accessed, the filtering logic is changed in the closure.
<!---arrayFilter.cfm---> 
<cfset filteredArray = arraynew(1)> 
<cfset componentArray = [3,6,8,2,4,7,9]> 
<cfscript> 
obj = CreateObject("component", "filter"); 
// Filters employees from India 
filteredArray = obj.filterArray(obj.getEmployee(), function(a) 
	{ 
	if(a.getLocation()=="IND") 
		return 1; 
	else 
		return 0; 
	}); 
writedump(filteredArray); 
//Filters employees from india whos age is above thirty 
filteredArray = obj.filterArray(obj.getEmployee(), closure(a) 
	{ 
	if((a.getLocation()=="IND") && (a.getAge()>30)) 
		return 1; 
	else 
		return 0; 
	}); 
writedump(filteredArray); 
// Filters employees who are managers 
filteredArray = obj.filterArray( obj.getEmployee(), function(a) 
	{ 
	if((a.getdesignation() contains "Manager")) 
		return 1; 
	else 
		return 0; 
	}); 
writedump(filteredArray); 
</cfscript>

This work is licensed under a Creative Commons Attribution-Noncommercial-Share Alike 3.0 Unported License  Twitter™ and Facebook posts are not covered under the terms of Creative Commons.

Legal Notices   |   Online Privacy Policy

Choose your region United States (Change)   Products   Downloads   Learn & Support   Company
Choose your region Close

Americas

Europe, Middle East and Africa

Asia Pacific

  • Brasil
  • Canada - English
  • Canada - Français
  • Latinoamérica
  • México
  • United States
  • Africa - English
  • Österreich - Deutsch
  • Belgium - English
  • Belgique - Français
  • België - Nederlands
  • България
  • Hrvatska
  • Cyprus - English
  • Česká republika
  • Danmark
  • Eesti
  • Suomi
  • France
  • Deutschland
  • Greece - English
  • Magyarország
  • Ireland
  • Israel - English
  • ישראל - עברית
  • Italia
  • Latvija
  • Lietuva
  • Luxembourg - Deutsch
  • Luxembourg - English
  • Luxembourg - Français
  • Malta - English
  • الشرق الأوسط وشمال أفريقيا - اللغة العربية
  • Middle East and North Africa - English
  • Moyen-Orient et Afrique du Nord - Français
  • Nederland
  • Norge
  • Polska
  • Portugal
  • România
  • Россия
  • Srbija
  • Slovensko
  • Slovenija
  • España
  • Sverige
  • Schweiz - Deutsch
  • Suisse - Français
  • Svizzera - Italiano
  • Türkiye
  • Україна
  • United Kingdom
  • Australia
  • 中国
  • 中國香港特別行政區
  • Hong Kong S.A.R. of China
  • India - English
  • 日本
  • 한국
  • New Zealand
  • Southeast Asia (Includes Indonesia, Malaysia, Philippines, Singapore, Thailand, and Vietnam) - English
  • 台灣

Commonwealth of Independent States

  • Includes Armenia, Azerbaijan, Belarus, Georgia, Moldova, Kazakhstan, Kyrgyzstan, Tajikistan, Turkmenistan, Ukraine, Uzbekistan

Copyright © 2016 Adobe Systems Incorporated. All rights reserved.

Terms of Use | Privacy | Cookies

AdChoices