Version: Flash 5 and later
Date Added: December 31, 2002
This technote is partly excerpted from ASDG2.
A standard function statement looks like this:
function doSomething () {
trace("Something was done!");
}
The same function can also be created with a function literal like this:
var doSomething = function () {
trace("Something was done!");
};
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
}
While these two approaches to creating a function yield very similar results, 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.