Functions are an important part of programming. The basic idea behind a function is to create one when you have repetitive blocks of code. For instance, if you are constantly getting the area of a rectangle, that is a perfect opportunity for a function. You create a function with the keyword function and then the name of the function followed by an opening parenthesis, which will hold any parameters you may want to put in the function, followed by a closing parenthesis. Then an opening curly bracket ({), after that, any code that you want to run, and then a return statement to send information back out of the function, followed, finally, by a closing curly bracket (}) on its own line. NOTE Not all functions need return statements, as you will see in Chapter 12, "Functions." Here is an example of creating and using a function to get the area of a rectangle: //create the function function getArea(width:Number, height:Number):Number{ //return the area in pixels return width * height; } //now call the function, and send the results to the output panel trace(getArea(20,31)); //Output: 620 The preceding code creates the function getArea, which has two parameters, width and height. In the function, it returns the width times the height. Then we call the function and send the result to the Output panel. You can clearly see the benefit of using functions. Now we can get the area of any rectangle on which we use the function. We could even send it information about a movie clip's width and height, and it will send back its area. For more on functions, see Chapter 12. |