Recipe 1.10 Exiting a Function

1.10.1 Problem

You want to exit a function.

1.10.2 Solution

Functions terminate automatically after the last statement within the function executes. Use a return statement to exit a function before reaching its end.

1.10.3 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");


ActionScript Cookbook
ActionScript 3.0 Cookbook: Solutions for Flash Platform and Flex Application Developers
ISBN: 0596526954
EAN: 2147483647
Year: 2005
Pages: 425

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