Understanding the ActionScript Language > Creating functions > Defining a function

 

Defining a function

Functions, like variables, are attached to the Timeline of the movie clip that defines them, and you must use a target path to call them. As with variables, you can use the _global identifier to declare a global function that is available to all Timelines without using a target path. To define a global function, precede the function name with the identifier _global, as in the following:

_global.myFunction = function (x) {
   return (x*2)+3;
}

To define a Timeline function, use the function action followed by the name of the function, any parameters to be passed to the function, and the ActionScript statements that indicate what the function does.

The following is a function named areaOfCircle with the parameter radius:

function areaOfCircle(radius) {
	return Math.PI * radius * radius;
}

Note: The keyword this, used in a function body, is a reference to the movie clip that the function belongs to.

You can also define a function by creating a function literal—an unnamed function that is declared in an expression instead of in a statement. You can use a function literal to define a function, return its value, and assign it to a variable in one expression, as in the following:

area = (function() {return Math.PI * radius *radius;})(5);
When a function is redefined, the new definition replaces the old definition.