Flash CS3 Documentation |
|||
| Learning ActionScript 2.0 in Adobe Flash > Functions and Methods > About functions and methods > About types of methods and functions > Writing named functions | |||
A named function is a kind of function that you commonly create in your ActionScript code to carry out all kinds of actions. When you create a SWF file, the named functions are compiled first, which means that you can reference the function anywhere in your code, as long as the function has been defined in the current or a previous frame. For example, if a function is defined in Frame 2 of a timeline, you cannot access that function in Frame 1 of the timeline.
The standard format for named functions is as follows:
function functionName(parameters) {
// function block
}
This piece of code contains the following parts:
functionName is the unique name of the function. All function names in a document must be unique.parameters contains one or more parameters that you pass to the function. Parameters are sometimes called arguments. For more information on parameters, see Passing parameters to a function. // function block contains all of the ActionScript code that's carried out by the function. This part contains the statements that "do stuff." You can put the code that you want to execute here. The // function block comment is a placeholder for where your code for the function block would go.
function myMessage() {
trace("mySoundID completed");
}
var my_sound:Sound = new Sound();
my_sound.attachSound("mySoundID");
my_sound.onSoundComplete = myMessage;
my_sound.start();
In this code you create a named function called myMessage, which you use later in the script to call a trace() function.
You use the function statement to create your own function in ActionScript. Remember that parameters are optional; however, if you don't have parameters, you still need to include the brackets. The content between the curly braces ({}) is called the function block.
You can write functions on the main timeline or within external ActionScript files, including class files.
You also write constructor functions in class files using this format (however, the name of the function matches the class). For more information on constructor functions, see Writing the constructor function. Also see Classes for information on and examples of writing functions in classes.
Flash CS3