About functions and methods 211
About function literals
A function literal is an unnamed function that you declare in an expression instead of in a
statement. Function literals are useful when you need to use a function temporarily or to use a
function in your code where you might use an expression instead. The syntax for a function
literal is:
function (param1, param2, etc) {
// statements
};
For example, the following code uses a function literal as an expression:
var yourName:String = "Ester";
setInterval(function() {trace(yourName);}, 200);
You can store a function literal in a variable to access it later in your code. To do so, you use an
anonymous function. For more information, see “Writing anonymous and callback functions”
on page 208.
About constructor functions
The constructor of a class is a special function that is called automatically when you create an
instance of a class by using the
new keyword (such as, var my_xml:XML = new XML();). The
constructor function has the same name as the class that contains it. For example, a custom
Person class that you create would contain the following constructor function:
public function Person(speed:Number) {
Person.numPeople++;
this._speed = speed;
}
Then you could create a new instance by using:
var myPerson:Person = new Person();
A class can contain only one constructor function; overloaded constructor functions are not
allowed in ActionScript 2.0. Also, a constructor function cannot have a return type. For more
information on writing constructor functions in class files, “Writing the constructor function”
on page 268.
NOTE
When you redefine a function literal, the new function definition replaces the old
definition.
NOTE
If you do not explicitly declare a constructor function in your class file—that is, if you don’t
create a function whose name matches that of the class—the compiler automatically
creates an empty constructor function for you.