1.8. Creating Reusable Code
Problem
You want to perform a series of actions at various times without duplicating code unnecessarily throughout your movie.
Solution
Create a function and then call (i.e., invoke) it by name whenever you need to execute those actions.
There is more than one way
to create (i.e., define or
declare) a function. Here is how to create a named
function:
function functionName ( ) {
// Statements go here.
}To call (i.e., execute) the named function, refer to it by name, such as:
functionName( );Here is how to create a function
literal:
functionName = function ( ) {
// Statements go here.
};Although not strictly required, it is considered a best practice to include a semicolon following the closing curly brace when defining a function literal.
Discussion
Grouping statements into a function allows you to define the function once but execute it as many times as you’d like. This is useful when you need to perform similar actions at various times without duplicating the same code in multiple places. Keeping your code centralized in functions makes it easier to understand (because you can write the function once and then ignore the details when using it) and easier to maintain (because you can make changes in one place rather than in multiple places).
There are two common ways of defining ActionScript functions: as
named functions or function literals (a.k.a. anonymous
functions). Each of these ways of declaring a function has
its own use.
The named function declaration ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access