220 Functions and Methods
3. Type the following code after the function:
var area:Number = getArea(10, 12);
trace(area); // 120
The getArea() function call assigns the values 10 and 12 to the width and height,
respectively, and you save the return value in the
area instance. Then you trace the values
that you save in the
area instance.
4. Select Control > Test Movie to test the SWF file.
You see
120 in the Output panel.
The parameters in the
getArea() function are similar to values in a local variable; they
exist while the function is called and cease to exist when the function exits.
In the next example, the ActionScript returns the value
NaN (not a number) if you don’t pass
enough parameters to the
addNumbers() function.
To pass a variable number of parameters to a function:
1. Create a new Flash document and save it as functionTest2.fla.
2. Add the following code to Frame 1 of the main Timeline:
function addNumbers(a:Number, b:Number, c:Number):Number {
return (a + b + c);
}
trace(addNumbers(1, 4, 6)); // 11
trace(addNumbers(1, 4)); // NaN (Not a Number), c equals undefined
trace(addNumbers(1, 4, 6, 8)); // 11
If you don’t pass enough parameters to the addNumbers function, the missing arguments
are assigned a default value of
undefined. If you pass too many parameters, the excess
parameters are ignored.
3. Select Control > Test Movie to test the Flash document.
Flash displays the following values: 11, NaN, 11.
Returning values from functions
You use the return statement to return values from functions. The return statement
specifies the value that is returned by a function. The
return statement returns the result of
an evaluation as a value of the function in which an expression executes. The
return
statement returns its result immediately to the calling code.
For more information, see
return statement in the ActionScript 2.0 Language Reference.