Functions are objects of the class Function. They can be declared on
their own, inside other functions, at package level, or as methods of a class, and
passed around like any other value.
Declaring a function
[attributes] function name(parameters)[:ReturnType] { statements } // statement
function [name](parameters)[:ReturnType] { statements } // expression
parameter := name[:Type] [= constant]
rest parameter := ...name[:Array] (last, at most one)
function area(width:Number, height:Number):Number {
return width * height;
}
var square:Function = function (side:Number):Number {
return side * side;
};
A function statement is hoisted: it can be called above the line that defines it,
anywhere in its scope. A function expression exists only from the moment it is
evaluated. In classes, methods are always written as statements; only statements can
take override and final.
Parameters and default values
- Arguments are passed by value; for objects the value is a reference, so the function can change the object but not the caller’s variable.
- A parameter with
= valueis optional. The value must be a compile-time constant: a literal number, string,true,false,null,NaN,undefinedor a constant. Every parameter after an optional one must be optional too. - Calling with too few or too many arguments is a compile error in strict mode and, for a function without a rest parameter, an
ArgumentError(1063, “Argument count mismatch”) at run time. ActionScript 2.0 allowed both. - A function’s
lengthproperty is the number of declared parameters.
function greet(name:String, greeting:String = "Hello", times:int = 1):void {
for (var i:int = 0; i < times; i++) {
trace(greeting + ", " + name);
}
}
greet("Ann"); // Hello, Ann
greet("Bob", "Hi", 2);
The rest parameter
...name as the last parameter collects every remaining argument into an
Array, which is empty when there are none. A function with a rest
parameter accepts any number of arguments.
function sum(...values):Number {
var total:Number = 0;
for each (var v:Number in values) total += v;
return total;
}
sum(1, 2, 3); // 6
function log(level:int, ...parts):void {
trace(level, parts.join(" "));
}
The arguments object
Inside a function without a rest parameter, arguments is an array-like
object of the values passed: arguments.length is how many, and
arguments[0] the first. arguments.callee is the function
itself, which lets an anonymous function call itself. There is no
arguments.caller. A function that declares ...rest cannot use
arguments, and a parameter named arguments hides it.
Return values
The type after the parameter list is checked on every return. A function
typed void returns undefined and may not return a value; one
with no return type may return anything. In strict mode a typed function must
return a value on every path through it.
Function closures
A function expression or nested function keeps the scope it was created in: its local variables and those of every enclosing function stay alive while the inner function can still be called. See Closures for the loop pitfall that follows from function scope.
function counter():Function {
var n:int = 0;
return function ():int { return ++n; };
}
var next:Function = counter();
next(); // 1
next(); // 2
Inside a function closure, this is whatever object the call is made on,
or the global object when it is called on its own, not the object whose code created
it.
Method closures
A method taken from an object, such as button.addEventListener(MouseEvent.CLICK,
onClick), stays bound to that object: this inside it is always the
instance it came from. This is new in ActionScript 3.0 (ActionScript 2.0 needed
Delegate.create), and it is why event listeners can be ordinary
methods.
public class Game extends Sprite {
private var score:int = 0;
public function Game() {
addEventListener(Event.ENTER_FRAME, tick);
}
private function tick(event:Event):void {
score++; // this is still the Game, even when called by the player
}
}
Passing the same method to removeEventListener later finds that
listener and removes it.
apply and call
| Method | Calls the function with |
|---|---|
f.call(thisArg, a, b, …) | this set to thisArg, and the arguments listed. |
f.apply(thisArg, argsArray) | this set to thisArg, and the elements of an array as arguments. |
For a method closure the thisArg is ignored: a bound method always runs
on its own instance. apply is the usual way to pass on a rest
parameter: target.apply(null, values).
Package-level and global functions
A function can be the single public definition of a file, inside the package block;
it is then imported like a class, as import flash.utils.getTimer; brings in
the package-level function getTimer. The top-level functions,
such as trace, parseInt and isNaN, need no
import; see Top-level API.