About functions and methods

Methods and functions are blocks of ActionScript code that you can reuse anywhere in a SWF file. You might write your functions in the FLA file or in an external ActionScript file and then call the function from anywhere within your documents. Methods are merely functions that are located within an ActionScript class definition. You can define functions to execute a series of statements on passed values. Your functions can also return values. After a function is defined, it can be called from any timeline, including a timeline of a loaded SWF file.

If you pass values as parameters to a function, the function can perform calculations using the supplied values. Each function has individual characteristics, and some functions require that you pass certain types or numbers of values. If you pass more parameters than the function requires, the function ignores the extra values. If you don't pass a required parameter, the function assigns the undefined data type to the empty parameters. This can cause errors during runtime. A function can also return values (see Returning values from functions).

NOTE

 

To call a function, that function's definition must be in a frame that the playhead has reached.

You can think of a well-written function as a "black box." If the function contains carefully placed comments about its input, output, and purpose, a person using the function does not need to understand exactly how it works internally.

The basic syntax for a simple named function is:

function traceMe() {
    trace("your message");
}
traceMe();

For information on writing named functions, see Writing named functions.

The basic syntax for a simple named function that builds on the previous example by passing a parameter, yourMessage, is:

function traceMe(yourMessage:String) {
    trace(yourMessage);
}
traceMe("How you doing?");

Alternatively, if you want to pass multiple parameters, you could use the following code:

var yourName:String = "Ester";
var yourAge:String = "65";
var favSoftware:String = "Flash";
function traceMe(favSoftware:String, yourName:String, yourAge:String) {
    trace("I'm " + yourName + ", I like " + favSoftware + ", and I'm " + yourAge + ".");
}
traceMe(favSoftware,yourName,yourAge);

For more information on passing parameters, see Passing parameters to a function.

There are numerous kinds of functions that you can write. For more information on writing functions, as well as links to sections on writing specific kinds of functions, see About types of methods and functions. For an example that compares methods and functions, see Understanding methods.

NOTE

 

For information on writing code using Script Assist, see Using Flash.

For more information about functions and methods, see the following topics:


Flash CS3