Table of Contents

9.1 Creating Functions

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

function funcName (param1, param2,...paramn) {
  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. The specified funcName must be a legal identifier[1], but otherwise it can be any unique name we choose (avoid creating functions with the same name as built-in functions). Next, we supply a pair of parentheses, (), that enclose any parameters (param1, param2, etc.), separated by commas, which we'll discuss later. If our function does not have any parameters, we include the parentheses but leave them 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 15 for the rules that govern legal identifiers.

Let's make a very simple function:

  1. Create a new empty Flash movie.

  2. On frame 1 of Layer 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( ). This simple function does not require any parameters. When we run it, the trace( ) statement in its body will be executed. Don't close the movie you've created; you'll learn to run the function next.


Table of Contents