User Guide
42 Chapter 1: ActionScript Basics
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 42
• “Passing parameters to a function” on page 42
• “Using variables in a function” on page 43
• “Returning values from a function” on page 43
• “Calling a user-defined function” on page 44
Defining a function
As with variables, you can use the
_global identifier to declare a global function that is available
to all 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;
}
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 24.
Passing parameters to a function
Parameters are the elements on which a function executes its code. (In this manual, the terms
parameter and argument are interchangeable.) For example, the following function takes the
parameters
initials and finalScore:
function fillOutScorecard(initials:String, finalScore:Number):Void {
scorecard.display = initials;
scorecard.score = finalScore;
}
When the function is called, the required parameters must be passed to the function. The
function substitutes the passed values for the parameters in the function definition. In this
example,
scorecard is the instance name of an object; display and score are properties of the
object. The following function call assigns the value
"JEB" to the variable display and the value
45000 to the variable score:
fillOutScorecard("JEB", 45000);