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:

To use a named function:

  1. Create a new document called namedFunc.fla.
  2. Import a short sound file into the library by selecting File > Import > Import to Library and selecting a sound file.
  3. Right-click the sound file and select Linkage.
  4. Type mySoundID in the Identifier text box.
  5. Select Frame 1 of the Timeline and add the following code to the Actions panel:
    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.

  6. Select Control > Test Movie to test the SWF file.

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