ActionScript: Generalizing a Function to Enhance Reusability

written by: Gabriel Savimbi; article published: year 2007, month 06;



In: Categories » Computers and technology » Flash » ActionScript: Generalizing a Function to Enhance Reusability

You want to perform slight variations of an action without having to duplicate multiple lines of code to accommodate the minor differences.

Add parameters to your function to make it flexible enough to perform slightly different actions when it is invoked rather than performing exactly the same action or producing the same result each time.

Define the parameters that account for the variability in what you want the function to do:

function myParamsFunction (param1, param2, param3) {
   trace("The average is " + (param1 + param2 + param3)/3);
   }

If you don't know the exact number of parameters the function will receive, use the built-in arguments array to handle a variable number of parameters.

A function that doesn't accept parameters generally produces the same result each time it is invoked. But you often need to perform almost exactly the same actions as an existing function, but with minor variations. Duplicating the entire function and then making minor changes to the second version is a bad idea in most cases. Usually, it makes your code harder to maintain and understand. More importantly, you'll usually find that you need not only two variations but many variations of the function. It can be a nightmare to maintain five or six variations of what should ideally be wrapped into a single function. The trick is to create a single function that can accept different values to operate on.

For example, if you have an average( ) function, you want to specify arbitrary values to be averaged each time it is invoked, instead of having it always average the same two numbers. You can accomplish this goal using parameters.

The most common way to work with parameters is to list them within the parentheses in the function declaration. The parameter names should be separated by commas, and when you invoke the function you should pass it a comma-delimited list of arguments that correspond to the parameters it expects.

The terms "parameters" and "arguments" are often used interchangeably to refer to the variables defined in the function declaration or the values that are passed to a function when it is invoked.

Here is a simple example of a function declaration using parameters and a function invocation in which arguments are passed during the function call:

// Define the function such that it expects two parameters: a and b.
   function average (a, b) {
   trace("The average is " + (a + b)/2);
   }
// When you invoke the function, pass it two arguments, such as 6 and 12, that 
   // correspond to the a and b parameters. 
   // This call to average(  ) displays: "The average is 9"
   average(6, 12);

Parameters work in exactly the same way with function literals as they do with named functions:

average = function (a, b) {
   trace("The average is: " + (a + b)/2);
   };

In most situations it is best to declare the parameters that the function should expect. However, there are some scenarios in which the number of parameters is unknown. For example, if you want the average( ) function to average any number of values, you can use the built-in arguments array, which is available within any function's body. All the parameters that are passed to a function are automatically placed into that function's arguments array.

// There is no need to specify the parameters 
   // to accept when using the arguments array.
   function average (  ) {
   var result = 0;
 // Loop through each of the elements of the arguments array 
   // and add that value to result.
   for (var i = 0; i < arguments.length; i++) {
   result += arguments[i];
   }
   // Then divide by the total number of arguments.
   trace("The average is " + result/arguments.length);
   }
// You can invoke average(  ) with any number of parameters. 
   // In this case, the function will display: "The average is 7.5".
 average (3, 6, 9, 12);

Technically, arguments is an object with additional properties beyond that of a basic array. However, while arguments is a special kind of array, you can still work with it in the same ways that you would a regular array.

legal disclaimer

1) Our website is not responsible for the information contained by this article as well for any and all copyright infringements by authors and writers. E-articles is a free information resource. If you suspect this article for any copyright infringements, please read the Terms of service and contact us to investigate the problem.
2) The E-articles directory team is not responsible for inaccuracies, falsehoods, or any other types of misinformation this tutorial may contain and will not be liable for any loss or damage suffered by a user through the user's reliance on the information gained here. Please read the Terms of service

Useful tools and features

Translate this article to...    Send this article to you or to a friend

Link to this article from your page   
If you like this article (tutorial), please link to it from your web page using the information above. Linking to this page, this is the only way to help us improve our service, the same time providing your visitors with a way to improve their online experience.

related articles

1. Drawing an Ellipse using ActionScript
Create a custom MovieClip.drawEllipse( ) method using the Drawing API and invoke it on a movie clip. You can create a method of the MovieClip class to draw an ellipse that is very similar to the drawCircle( ) method. In fact, the drawCircle( ) method is merely a degenerate version of drawEllipse( ), in which the radii in the x and y directions are the same. The custom drawEllipse( ) method accepts four parameters: xRadius The radius of the ellipse in the x direction (major axis). yRadius ...

2. ActionScript: Filling a Shape with a Gradient
Use the beginGradientFill( ) and endFill( ) methods to initiate and close a shape drawn at runtime. In a gradient fill, there is a graded change in colors. Flash supports linear gradients, in which one color fades into the next from left to right. Flash also supports radial gradients, in which the colors radiate out from a center point. You can initiate a gradient-filled shape using beginGradientFill( ) in the same way you initiate a solid-filled shape with beginFill( ). The difference is that the call to beginGradientFill( ) require...

3. Scripting Masks in Flash
Use the Drawing API to create a shape and then use MovicClip.setMask( ) to apply the mask. Masks can be used to create unique shapes or visual effects. For example, you can use masks to create wipes and transitions or interesting animations in which only the masked portion of the artwork is visible at a given time. You can even create masks that change shape over time, and use them to mask bitmapped graphics (in movie clips). You can use any movie clip as a mask of another movie clip using the setMask( ) method. The setMask( ...

4. Drawing a Triangle using ActionScript
Create a custom MovieClip.drawTriangle( ) method using the Drawing API and invoke it on a movie clip. You can determine and plot the vertices of a triangle given the lengths of two sides and the angle between them. This is a better approach than specifying the lengths of the three sides because knowing the lengths of two sides and the angle between them always determines a triangle, whereas three arbitrary sides may not fit together to make a triangle. The custom drawTriangle( ) method accepts six parameters: ab ...

5. ActionScript: Filling a Shape with a Solid or Translucent Color
Use the beginFill( ) and endFill( ) methods to initiate and close a shape drawn at runtime. To draw a filled shape, call beginFill( ) prior to any other drawing methods, including the custom methods you have defined such as drawCircle( ) and drawPolygon( ). Invoke endFill( ) after calling other drawing methods to create the shape. You cannot apply a fill to an existing shape drawn at authoring time or runtime. You must invoke beginFill( ) before drawing the shape to be filled. This example creates a solid blue ...

6. Drawing a rectangle using ActionScript
Create a custom MovieClip.drawSimpleRectangle( ) method using the Drawing API and invoke it on a movie clip. To draw a simple rectangle, specify the stroke's attributes using the lineStyle( ) method and then draw four lines using the lineTo( ) method: // Create rectangle_mc with a depth of 1 on the main timeline. _root.createEmptyMovieClip("rectangle_mc", 1); // Specify a one-pixel, solid, black line. rectangle_mc.lineStyle(1, 0x000000, 100); // Draw four lines to form the perimeter ...

7. How to draw a rectangle with rounded corners
You want to draw a rectangle with rounded corners, an offset, or rotation.Create a custom MovieClip.drawRectangle( ) method using the Drawing API and invoke it on a movie clip. The drawSimpleRectangle( ) method is, as the name suggests, quite simple. Let's create a more complex version that also: Draws a rectangle with a specified angle of rotation Let's you specify the rectangle center's coordinates Can draw a rectangle with rounded corners The drawRectangle( ) method accepts...

8. Reusing and Organizing Code in Flash Movies
You want to reuse code that you've created for one project in another Flash movie. Or you want to write your ActionScript code in an external text editor. Place your ActionScript code in external .as files and use the #include directive to add them to your Flash movies: // Adds all the code within MyActionScriptFile.as to your Flash movie. #include "MyActionScriptFile.as" Use the #include directive to incorporate code from external text files into your Flash movie during compilation from a .fla file ...

9. Drawing a Circle using ActionScript
Create a custom MovieClip.drawCircle( ) method using the Drawing API and invoke it on a movie clip. You can create a circle in ActionScript with eight curves. Fewer curves results in a distorted circle and too many curves hinders performance. Let's create a custom method of the MovieClip class for drawing circles. This method, drawCircle( ), allows for three parameters: radius The radius of the circle x The x coordinate of the circle's center point. If undefined, the circle is centered at x =...

10. ActionScript: Repeating a Task at Timed Intervals
You want to perform an action or actions at a specific timed interval. Use the setInterval( ) function. The setInterval( ) function allows you to specify an interval (in milliseconds) at which your Flash movie will invoke a function. Use setInterval( ) to perform a particular action over time but not necessarily at the frequency of the frame rate of the movie. // Define a function. function myIntervalFunction ( ) { // Output the difference between the current timer value and its value from the ...