Chapter 9. FunctionsContents:
Creating 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:
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 FunctionsTo 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.
Let's make a (very) simple function:
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. Copyright © 2002 O'Reilly & Associates. All rights reserved. |
|