User Guide

116 Object-Oriented Programming in ActionScript
Methods are defined using the function keyword. You can use a function statement, such as
the following:
public function sampleFunction():String {}
Or you can use a variable to which you assign a function expression, as follows:
public var sampleFunction:Function = function () {}
In most cases you will want to use a function statement instead of a function expression for
the following reasons:
Function statements are more concise and easier to read.
Function statements allow you to use the override and final keywords. For more
information, see “Overriding methods” on page 134.
Function statements create a stronger bond between the identifier—that is, the name of
the function—and the code within the method body. Because the value of a variable can
be changed with an assignment statement, the connection between a variable and its
function expression can be severed at any time. Although you can work around this issue
by declaring the variable with
const instead of var, such a technique is not considered a
best practice because it makes the code hard to read and prevents the use of the
override
and
final keywords.
One case in which you must use a function expression is when you choose to attach a function
to the prototype object. For more information, see “The prototype object” on page 144.
Constructor methods
Constructor methods, sometimes simply called constructors, are functions that share the same
name as the class in which they are defined. Any code that you include in a constructor
method is executed whenever an instance of the class is created with the
new keyword. For
example, the following code defines a simple class named Example that contains a single
property named
status. The initial value of the status variable is set inside the constructor
function.
class Example
{
public var status:String;
public function Example()
{
status = "initialized";
}
}
var myExample:Example = new Example();
trace (myExample.status); // output: initialized