Passing Information to Functions

In the last section, we created a function that executed a simple trace( ) statement—not exactly the most compelling specimen of the function species. Here’s a more interesting function that moves a movie clip instance named ball a short distance:

function moveBall ( ) {
  ball._x += 10;
  ball._  y += 10;
}

With the function moveBall( ) defined, we can move ball diagonally anytime by calling the moveBall( ) function:

moveBall( );

The ball moves diagonally down and to the right. (Note that the origin (0, 0) is in the upper left of the main Stage. Increasing values of _x move the ball to the right, but unlike the Cartesian coordinates, increasing values of _ y move the ball down, not up.)

Our moveBall( ) function is convenient, but it lacks flexibility. It works only on one movie clip (ball), it moves ball in only one direction, and it always moves ball the same distance.

A well-designed function should define a single code segment that works in many circumstances. We can generalize our moveBall( ) function so that it can move any clip any distance in any direction. The first step in generalizing any function is determining what factors control its behavior. In our moveBall( ) function, the factors are the name of the movie clip to move, the distance to move it horizontally, and the distance to move it vertically. Such factors are known as the parameters of the function—they’re the information that we’d like to be able to adjust when the function is called. ...

Get ActionScript: The Definitive Guide now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.