O'Reilly logo

Essential ActionScript 3.0 by Colin Moock

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Function Literal Syntax

As with many of ActionScript's native classes, instances of the Function class can be created with literal syntax. Function literals have the same syntax as standard function declarations, except that the function name is omitted. The general form is:

function (param1,param2, ...paramn) {
}

where param1, param2, ...paramn is an optional list of parameters.

To use the function defined by a function literal outside the expression in which the literal occurs, we can assign it to a variable, as shown in the following code:

var someVariable = function (param1,param2, ...paramn) {
}

Once assigned, the function can then be invoked through that variable, as in:

someVariable(arg1, arg2, ...argn)

For example, the following code uses a function literal to create a function that squares a number and assigns that function to the variable square:

var square = function (n) {
  return n * n;
}

To invoke the preceding function, we use the following code:

// Squares the number 5     and returns the result
square(5)

Function literals are sometimes used with the built-in function flash.utils.setInterval( ), which takes the following form:

setInterval(functionOrMethod, delay)

The setInterval( ) function starts an interval, which automatically executes a specified function or method (functionOrMethod) every delay milliseconds. When an interval is created, it is assigned a number, known as an interval ID, that is returned by setInterval( ). The interval ID can be assigned to a variable so that the ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required