About functions and methods 221
The following rules govern how to use the return statement in functions:
■ If you specify a return type other than Void for a function, you must include a return
statement and it must be followed by the returned value in the function.
■ If you specify a return type of Void, you do not need to include a return statement, but if
you do, it must not be followed by any value.
■ Regardless of the return type, you can use a return statement to exit from the middle of a
function.
■ If you don’t specify a return type, including a return statement is optional.
For example, the following function returns the square of the parameter
myNum and specifies
that the returned value must be a Number data type:
function sqr(myNum:Number):Number {
return myNum * myNum;
}
Some functions perform a series of tasks without returning a value. The next example returns
the processed value. You are capturing that value in a variable, and then you can use that
variable within your application.
To return a value and capture it in a variable:
1. Create a new Flash document and save it as return.fla.
2. Add the following code to Frame 1 of the main Timeline:
function getArea(width:Number, height:Number):Number {
return width * height;
}
The getArea() function takes two parameters, width and height.
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.