View comments | RSS feed

Using function names as function arguments

Because function names are ColdFusion variables, you can pass a function's name as an argument to another function. This technique allows a function to use another function as a component. For example, a calling page can call a calculation function, and pass it the name of a function that does some subroutine of the overall function.

This way, the calling page could use a single function for different specific calculations, such as calculating different forms of interest. The initial function provides the framework, while the function whose name is passed to it can implement a specific algorithm that is required by the calling page.

The following simple example shows this use. The binop function is a generalized function that takes the name of a function that performs a specific binary operation and two operands. The binop function simply calls the specified function and passes it the operands. This code defines a single operation function, the sum function. A more complete implementation would define multiple binary operations.

<cfscript>
function binop(operation, operand1, operand2)
{ return (operation(operand1, operand2)); }
function sum(addend1, addend2)
{ return addend1 + addend2;}
x = binop(sum, 3, 5);
writeoutput(x);
</cfscript>

ColdFusion 9 | ColdFusion 8 | ColdFusion MX 7 | ColdFusion MX 6.1 | ColdFusion MX | Forums | Developer Center | KnowledgeBase | Bug Reporting

Version 7

Comments


Ashish-Saxena said on Jul 23, 2007 at 2:12 AM :
The above code functionality can be worked out by CfFunction tag also:

<cffunction name="binop">
<cfargument name="operation">
<cfargument name="operand1">
<cfargument name="operand2">

<!--- Use pound sign, always to get the value of variables. --->
<cfinvoke method="#operation#" returnvariable="total" >
<cfinvokeargument name="addend1" value="#operand1#">
<cfinvokeargument name="addend2" value="#ARGUMENTS.operand2#">
</cfinvoke>

<cfreturn total>
</cffunction>

<cffunction name="sum">
<cfargument name="addend1">
<cfargument name="addend2">
<cfreturn addend1 + addend2>
</cffunction>

<cfinvoke method="binop" returnvariable="x">
<cfinvokeargument name="operation" value="sum">
<cfinvokeargument name="operand1" value="3">
<cfinvokeargument name="operand2" value="5">
</cfinvoke>

<cfoutput>#x#</cfoutput>

OUTPUT:
8

 

RSS feed | Send me an e-mail when comments are added to this page | Comment Report

Current page: http://livedocs.adobe.com/coldfusion/7/htmldocs/00001017.htm