Table of Contents

9.5 Function Literals

ActionScript allows us to create function literals, which are convenient when we need a function temporarily or when we want to use a function where an expression is expected.

Function literals have the same syntax as standard function declarations, except that the function name is omitted and there's a semicolon after the statement block. The general form is:

identifier = function (param1, param2, ...paramn) { statements };

where param1, param2, ...paramn is an optional list of parameters and statements is one or more statements that constitute the function body. Because it doesn't include a function name, a function literal's definition is "lost" unless we store it in a variable (or an array element or object property). We can store a function literal in a variable for later access, like this:

// Store a function literal in a variable
var mouseCoords = function () { return [ _xmouse, _ymouse ]; };
// Now we can execute the function
mouseCoords();

Note that because ActionScript does not support JavaScript's Function( ) constructor, dynamic functions cannot be composed at runtime, as they can in JavaScript.

As we'll see in Chapter 12, function literals are often used when assigning methods to classes or objects. For example:

Ball.prototype.startMoving = function ( ) {
  // Movement code goes here
};

is the same as:

Ball.prototype.startMoving = startMoving;
function startMoving ( ) {
  // Movement code goes here
}

However, there are three subtle differences between function literals and standard function declarations:


Table of Contents