User Guide

Functions 91
} while (i < 5);
// output: 5
Functions
Functions are blocks of code that carry out specific tasks and can be reused in your program.
There are two types of functions in ActionScript 3.0: methods and function closures. Whether a
function is a called a method or a function closure depends on the context in which the
function is defined. A function is called a method if you define it as part of a class definition
or attach it to an instance of an object. A function is called a function closure if it is defined in
any other way.
Functions have always been extremely important in ActionScript. In ActionScript 1.0, for
example, the
class keyword did not exist, so “classes” were defined by constructor functions.
Although the
class keyword has since been added to the language, a solid understanding of
functions is still important if you want to take full advantage of what the language has to offer.
This can be a challenge for programmers who expect ActionScript functions to behave
similarly to functions in languages such as C++ or Java. Although basic function definition
and invocation should not present a challenge to experienced programmers, some of the more
advanced features of ActionScript functions require some explanation.
Basic function concepts
This section discusses basic function definition and invocation techniques.
Calling functions
You call a function by using its identifier followed by the parentheses operator (()). You use
the parentheses operator to enclose any function parameters you want to send to the function.
For example, the
trace() function, which is a top-level function in the Flash Player API, is
used throughout this book:
trace(“Use trace to help debug your script”);
If you are calling a function with no parameters, you must use an empty pair of parentheses.
For example, you can use the
Math.random() method, which takes no parameters, to
generate a random number:
var randomNum:Number = Math.random();