9.5 Function Literals

ActionScript for Flash MX: The Definitive Guide, 2nd Edition
By Colin Moock
Chapter 9.  Functions

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:

  • When assigned as a method, a function literal does not leave an extraneous function reference defined in the scope of the function declaration. For example, in the first Ball example (assuming the Ball code is attached to the main timeline), a function literal is stored in Ball.prototype.startMoving and no separate function reference remains defined on _root. But in the second example, a reference to startMoving( ) exists both in Ball.prototype.startMoving and on _root.

  • A standard function declaration does not end in a semicolon, whereas a function literal does.

  • Functions created with function statements are available throughout an entire script, even to statements that come before the function declaration statement (on the same keyframe or within the same onClipEvent( ) or on( ) event handler). Function literals are available only to statements that come after the literal in the script.

     



    ActionScript for Flash MX. The Definitive Guide
    ActionScript for Flash MX: The Definitive Guide, Second Edition
    ISBN: 059600396X
    EAN: 2147483647
    Year: 2002
    Pages: 780
    Authors: Colin Moock

    flylib.com © 2008-2017.
    If you may any questions please contact us: flylib@qtcs.net