9.2 Running Functions

ActionScript for Flash MX: The Definitive Guide, 2nd Edition
By Colin Moock
Chapter 9.  Functions

We run a function like a wizard invokes a spell, by proclaiming the function's name, followed by the function call operator, (), introduced in Chapter 5:

funcName(param1, param2,...paramn)

(You can almost detect the faint odor of smoldering mandrake root in the air.)

The parentheses contain the values for any parameters required by the function. If the function requires no parameters (as determined by the function declaration), the parentheses are left empty. Let's try invoking our sayHi( ) function, which has no parameters, to get the hang of basic function invocation.

Here, again, is our sayHi( ) function declaration:

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

And here's our sayHi( ) function invocation:

sayHi();

In this simple demonstration, we add the function invocation to the same script containing the function declaration, but we'll see later that this isn't always the case. When the sayHi( ) function call is executed, the sayHi function is invoked, so its function body runs, causing "Hi there!" to appear in the Output window.

You can see that typing sayHi( ); is more convenient than typing the whole trace( ) statement, and the function name, sayHi, is a more meaningful description of what our code does. Using thoughtful function names makes our code more readable, almost like human sentences. In this book and in most programming documentation, function names are conventionally listed with the invocation parentheses, as in "the sayHi( ) function" versus "the sayHi function." This convention makes function names easy to spot in a sentence.

Before we continue, notice the semicolon at the end of the function call:

sayHi();

We add the semicolon because a function call is a complete statement, and good form dictates that all statements should end in a semicolon.

Believe it or not, you've just learned the basics of creating and invoking functions not too shabby. Functions keep our code centralized and easier to maintain, especially when we need to perform the same operation repeatedly throughout our program. Functions become even more powerful when used with parameters, which we'll consider next.

     



    ActionScript for Flash MX. The Definitive Guide
    ActionScript for Flash MX: The Definitive Guide, Second Edition
    ISBN: 059600396X
    EAN: 2147483647
    Year: 2002
    Pages: 780
    Authors: Colin Moock

    flylib.com © 2008-2017.
    If you may any questions please contact us: flylib@qtcs.net