1.10. Exiting a Function
Problem
You want to exit a function.
Solution
Functions terminate
automatically after the last statement
within the function executes. Use a return
statement
to exit a function before reaching
its end.
Discussion
The return statement exits the current function,
and the ActionScript interpreter continues the execution of the
script that initially invoked the function. Any statements within the
function body that follow a return statement are
ignored.
function myFunction ( ) {
return;
trace("Never called");
}
myFunction( );
// Execution continues here after returning from the myFuction( ) invocation.In the preceding example, the return statement
causes the function to terminate before performing any actions, so it
is not a very useful function. More commonly, you will use a
return statement to exit a function under
certain conditions. This example exits the function if the password
is wrong:
function checkPassword (password) {
// If password is not "SimonSays", exit the function.
if (password != "SimonSays") {
return;
}
// Otherwise, perform the rest of the actions.
gotoAndStop ("TreasureMap");
}
// This function call uses the wrong password, and so the function exits.
checkPassword("MotherMayI");
// This function uses the correct password, and so the function jumps to the
// TreasureMap frame.
checkPassword("SimonSays");Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access