About functions and methods 213
Targeting and calling user-defined functions
User-defined functions are simply functions that you create yourself to use in applications, as
opposed to functions in built-in classes that perform predefined functions. You name the
functions yourself and add statements in the function block. Previous sections cover writing
functions such as named, unnamed, and callback functions. For information on naming
functions, see “Naming functions” on page 214, and for information on using functions, see
“Using functions in Flash” on page 214.
You can use a target path to call a function in any timeline from any timeline, including from
a timeline of a loaded SWF file. To call a function, type the target path to the name of the
function, if necessary, and pass any required parameters inside parentheses. There are several
forms of syntax for user-defined functions. The following code uses a path to call the
initialize() function, which was defined on the current timeline and requires
no parameters:
this.initialize();
The following example uses a relative path to call the list() function, which was defined in
the
functionsClip movie clip:
this._parent.functionsClip.list(6);
For information on writing named functions, see “Writing named functions” on page 207.
For more information on parameters, see “Passing parameters to a function” on page 218.
You can also define your own named functions. For example, the following named function
helloWorld() is user defined:
function helloWorld() {
trace("Hello world!");
};
The following example shows you how to use a user-defined function in a FLA file.
To create and call a simple user-defined function:
1. Create a new Flash document and save it as udf.fla.
2. Add the following ActionScript to Frame 1 of the main Timeline:
function traceHello(name:String):Void {
trace("hello, " + name + "!");
}
traceHello("world"); // hello, world!
The previous code creates a user-defined function named traceHello() that takes one
argument,
name, and traces a greeting message. To call the user-defined function, you can
call
traceHello from the same timeline as the function definition and pass a single
string value.