User Guide
Functions 95
There are two subtle differences between function statements and function expressions that
you should take into account when choosing which technique to use. The first difference is
that function expressions do not exist independently as objects with regard to memory
management and garbage collection. In other words, when you assign a function expression to
another object, such as an array element or an object property, you create the only reference to
that function expression in your code. If the array or object to which your function expression
is attached goes out of scope or is otherwise no longer available, you will no longer have access
to the function expression. If the array or object is deleted, the memory that the function
expression uses will become eligible for garbage collection, which means that the memory is
eligible to be reclaimed and reused for other purposes.
The following example shows that for a function expression, once the property to which the
expression is assigned is deleted, the function is no longer available. The class Test is dynamic,
which means that you can add a property named
functionExp that holds a function
expression. The
functionExp() function can be called with the dot operator, but once the
functionExp property is deleted, the function is no longer accessible.
dynamic class Test {}
var myTest:Test = new Test();
// function expression
myTest.functionExp = function () { trace("Function expression") };
myTest.functionExp(); // Function expression
delete myTest.functionExp;
myTest.functionExp(); // error
If, on the other hand, the function is first defined with a function statement, it exists as its
own object, and continues to exist even after you delete the property to which it is attached.
The
delete operator only works on properties of objects, so even a call to delete the function
stateFunc() itself does not work.
dynamic class Test {}
var myTest:Test = new Test();
// function statement
function stateFunc() { trace("Function statement") }
myTest.statement = stateFunc;
myTest.statement(); // Function statement
delete myTest.statement;
delete stateFunc; // no effect
stateFunc(); // Function statement
myTest.statement(); // error