212 Functions and Methods
Defining global and timeline functions
In “About functions and methods” on page 201, you explored the different kinds of functions
that are available in Flash. As with variables, functions are attached to the timeline of the
movie clip that defines them, and you must use a target path to call them. As with variables,
you can use the
_global identifier to declare a global function that is available to all timelines
and scopes without using a target path. To define a global function, precede the function
name with the identifier
_global, as shown in the following example:
_global.myFunction = function(myNum:Number):Number {
return (myNum * 2) + 3;
};
trace(myFunction(5)) // 13
For information on _global and scope, “About variables and scope” on page 96.
To define a timeline function, use the
function statement followed by the name of the
function, any parameters to be passed to the function, and the ActionScript statements that
indicate what the function does.
The following example is a function named
areaOfCircle with the parameter radius:
function areaOfCircle(radius:Number):Number {
return (Math.PI * radius * radius);
}
trace(areaOfCircle(8));
You can also define functions in numerous other ways. For more information on each kind of
function, see the following sections:
■ “About built-in and top-level functions” on page 205
■ “Writing named functions” on page 207
■ “Writing anonymous and callback functions” on page 208
■ “About function literals” on page 211
■ “About constructor functions” on page 211
■ “Targeting and calling user-defined functions” on page 213
For information on naming functions, see “Naming functions” on page 214. For a detailed
example of using functions in an external class file, see “Using functions in Flash” on page 214
and Chapter 7, “Classes,” on page 225.
NOTE
For information on writing code using Script Assist, see “Using Script Assist to write
ActionScript” on page 328, “Creating a startDrag/stopDrag event using Script Assist”
on page 331 and the ActionScript:Use Script Assist Mode tutorial (which begins with
“Open the starter document” on page 213).