home | O'Reilly's CD bookshelfs | FreeBSD | Linux | Cisco | Cisco Exam  


Book HomeActionScript: The Definitive GuideSearch this book

Chapter 9. Functions

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 programming 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 Chapter 12, "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:

Function declaration

Creating functions to use in our scripts.

Function invocation

Causing functions to execute. In other words, running the code in a function. Also known as calling a function.

Function arguments and parameters

Providing functions with data to manipulate upon invocation.

Function termination

Ending the execution of a function and optionally returning a result.

Function scope

Determining the availability and life span of a function, and the accessibility of variables referenced in a function body.

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!

9.1. 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 Chapter 14, "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.



Library Navigation Links

Copyright © 2002 O'Reilly & Associates. All rights reserved.