Functions as objects

Functions in ActionScript 3.0 are objects. When you create a function, you are creating an object that can not only be passed as a parameter to another function, but also have properties and methods attached to it.

Functions passed as arguments to another function are passed by reference and not by value. When you pass a function as an argument, you use only the identifier and not the parentheses operator that you use to call the method. For example, the following code passes a function named clickListener() as an argument to the addEventListener() method:

addEventListener(MouseEvent.CLICK, clickListener);

The Array.sort() method also defines a parameter that accepts a function. For an example of a custom sort function that is used as an argument to the Array.sort() function, see Sorting an array.

Although it may seem strange to programmers new to ActionScript, functions can have properties and methods, just as any other object can. In fact, every function has a read-only property named length that stores the number of parameters defined for the function. This is different from the arguments.length property, which reports the number of arguments sent to the function. Recall that in ActionScript, the number of arguments sent to a function can exceed the number of parameters defined for that function. The following example, which compiles only in standard mode because strict mode requires an exact match between the number of arguments passed and the number of parameters defined, shows the difference between the two properties:

// Compiles only in standard mode 
function traceLength(x:uint, y:uint):void 
{ 
    trace("arguments received: " + arguments.length); 
    trace("arguments expected: " + traceLength.length); 
} 
 
traceLength(3, 5, 7, 11); 
/* output: 
arguments received: 4 
arguments expected: 2 */

In standard mode you can define your own function properties by defining them outside your function body. Function properties can serve as quasi-static properties that allow you to save the state of a variable related to the function. For example, you may want to track the number of times a particular function is called. Such functionality could be useful if you are writing a game and want to track the number of times a user uses a specific command, although you could also use a static class property for this. The following example, which compiles only in standard mode because strict mode does not allow you to add dynamic properties to functions, creates a function property outside the function declaration and increments the property each time the function is called:

// Compiles only in standard mode 
var someFunction:Function = function ():void 
{ 
    someFunction.counter++; 
} 
 
someFunction.counter = 0; 
 
someFunction(); 
someFunction(); 
trace(someFunction.counter); // 2