Functions

Contents:

Creating Functions
Running Functions
Passing Information to Functions
Exiting and Returning Values from Functions
Function Literals
Function Availability and Life Span
Function Scope
Function Parameters Revisited
Recursive Functions
Internal Functions
Functions as Objects
Centralizing Code
The Multiple-Choice Quiz Revisited
Onward!

I'm almost giddy to tell you about functions because they're such a powerful part of ActionScript. A function is simply a chunk of code that can be reused throughout a program. Not only do functions lend enormous flexibility and convenience to our scripts, they also give us control over Flash movie elements. I can hardly imagine developing without functions -- they ease everything from sorting words to calculating the distance between two movie clips. We'll introduce functions in this chapter before learning how to create complex, powerful programs using functions with objects in "Objects and Classes".

We'll focus first on program functions -- the functions we create ourselves in our scripts. By learning to create our own functions, we'll become familiar with these fundamentals:

Once we understand those aspects of functions, we'll consider how they apply to internal functions, functions that come built into ActionScript. Let's get to it!

Creating Functions

To make a basic function we simply need a function name and a block of statements to perform, like this:

function funcName ( ) {
 statements }

The function keyword starts the declaration of our new function. Next comes our function name, funcName, which we'll use later to invoke our function. funcName must be a legal identifier.[1] Next, we supply a pair of parentheses, ( ), that enclose any optional parameters, which we'll discuss later. If our function does not have any parameters, we leave the parentheses empty. Finally, we provide the function body (i.e., statement block), which contains the code that's executed when our function is called.

[1]See "Lexical Structure", for the rules that govern legal identifiers.

Let's make a (very) simple function:

  1. Start a new Flash movie.
  2. On frame 1 of the main movie timeline, attach the following code:

    function sayHi ( ) {
     trace("Hi there!");
    }
    


That was easy -- we've just created a function named sayHi( ). When we run it, the trace( ) statement in its body will be executed. Don't close the movie you've created, we'll learn to run our function next.