Recipe 1.15.
Exiting a Method
Problem
You want to
exit a method.
Solution
Methods terminate automatically after the last
statement within the method executes. Use a return statement to exit a method
before reaching its end.
Discussion
The return statement exits the current
method and the ActionScript interpreter continues execution of the
code that initially invoked the method. Any statements within the
method body that follow a return statement are ignored.
private function sampleFunction ( ):void {
return;
trace("Never called");
}
// Called from within another method:
sampleFunction( );
// Execution continues here after returning from the sampleFuction( ) invocation
In the preceding example, the return
statement causes the method to terminate before performing any
actions, so it isn't a very useful method. More commonly, you will
use a return statement to exit a method under certain
conditions. This example exits the method if the password is
wrong:
private function checkPassword (password:String):void {
// If password is not "SimonSays", exit the function.
if (password != "SimonSays") {
return;
}
// Otherwise, perform the rest of the actions.
showForm ("TreasureMap");
}
// This method call uses the wrong password, so the
// function exits.
checkPassword("MotherMayI");
// This method call uses the correct password, so the function
// shows the TreasureMap form.
checkPassword("SimonSays");
In the preceding example, you may notice that
the method is declared as void, yet it is possible to use
a return statement within the method without getting a
compiler error. When a return statement is used simply to
exit from a method, it is valid within a method declared as
void.
|
In ActionScript 2.0, the function was
Void. In ActionScript 3.0, it is lowercase
void.
|
|
However, if you attempt to actually return a
value in such a method, the compiler generates an error.
private function sampleMethod ( ):void {
return "some value"; // This causes the compiler to generate an error.
}
|