Recipe 1.16. Obtaining the Result of a Method


Problem

You want to perform some method and return the results to the statement that invoked the function.

Solution

Use a return statement that specifies the value to return.

Discussion

When used without any parameters, the return statement simply terminates a method. However, any value specified after the return keyword is returned to statement that invoked the method. Usually, the returned value is stored in a variable for later use. The datatype of the return value must match the return type of the method:

private function average (a:Number, b:Number):Number {   return (a + b)/2; }

Now we can call the average( ) method and store the result in a variable and use the result in some way.

var playerScore:Number = average(6, 10); trace("The player's average score is " + playerScore);

You can use the return value of a method, without storing it in a variable, by passing it as a parameter to another function, such as:

trace("The player's average score is " + average(6, 10));

Note, however, that if you do nothing with the return value of the function, the result is effectively lost. For example, this statement has no detectable benefit because the result is never displayed or used in any way:

average(6, 10);




ActionScript 3. 0 Cookbook
ActionScript 3.0 Cookbook: Solutions for Flash Platform and Flex Application Developers
ISBN: 0596526954
EAN: 2147483647
Year: 2007
Pages: 351

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net