The second way to declare a function is to use an assignment statement with a function literal, which is also sometimes called an anonymous function. This is a more verbose method that is widely used in earlier versions of ActionScript.
An assignment statement with a function literal begins with the var keyword, followed by:
An assignment statement with a function literal begins with the var keyword, followed by:
- the function name;
- the colon operator (:);
- the Function keyword used to indicate the data type;
- the assignment operator (=);
- the function keyword
- the parameters, in a comma-delimited list enclosed in parentheses;
- the function body, that is, the ActionScript code to be executed when the function is invoked, enclosed in curly braces.
For example, the following code declares the traceParameter function using a function literal:
var traceParameter:Function = function (aParam:String) {
trace(aParam);
};
traceParameter("hello"); // Output: hello
Note that you do not specify a function name, as you do in a function statement. Another important difference between function literals and function statements is that a function literal is an expression rather than a statement. This means that a function literal cannot stand on its own, as a function statement can. A function literal can only be used as a part of a statement, usually an assignment statement. The following example shows a function literal assigned to an array element:
var traceArray:Array = new Array();
traceArray[0] = function (aParam:String) {
trace(aParam);
};
traceArray[0]("hello");