User Guide
Creating functions 61
Creating functions
You can define functions to execute a series of statements on passed values. Your functions can
also return values. After a function is defined, it can be called from any Timeline, including the
Timeline of a loaded SWF file.
A well-written function can be thought of as a “black box.” If it has carefully placed comments
about its input, output, and purpose, a user of the function does not need to understand exactly
how the function works internally.
For more information, see the following topics:
• “Defining a function” on page 61
• “Passing parameters to a function” on page 62
• “Using variables in a function” on page 62
• “Returning values from a function” on page 62
• “Calling a user-defined function” on page 63
Defining a function
As with variables, functions are attached to the Timeline of the movie clip that defines them, and
you must use a target path to call them. As with variables, you can use the
_global identifier to
declare a global function that is available to all Timelines and scopes without using a target path.
To define a global function, precede the function name with the identifier
_global, as shown in
the following example:
_global.myFunction = function (x:Number):Number {
return (x*2)+3;
}
To define a Timeline function, use the function statement followed by the name of the function,
any parameters to be passed to the function, and the ActionScript statements that indicate what
the function does.
The following example is a function named
areaOfCircle with the parameter radius:
function areaOfCircle(radius:Number):Number {
return Math.PI * radius * radius;
}
You can also define a function by creating a function literal—an unnamed function that is
declared in an expression instead of in a statement. You can use a function literal to define a
function, return its value, and assign it to a variable in one expression, as shown in the
following example:
area = (function() {return Math.PI * radius *radius;})(5);
When a function is redefined, the new definition replaces the old definition.
For information on strictly typing function return types and parameters, see “Strict data typing”
on page 41.