Professional Documents
Culture Documents
Simulating Multiple Constructor Functions
Simulating Multiple Constructor Functions
Unlike Java, ActionScript does not support multiple constructor functions for a single class
(referred to as overloaded constructors in Java). In Java, a class can initialize an instance
differently depending on the number and type of arguments used with the new operator. In
ActionScript, similar functionality must be implemented manually. Example 4-5, based on
our Box class, shows one possible way to simulate multiple constructor functions in
ActionScript..
In Example 4-5, the Box constructor delegates its work to three pseudo-constructor
methods, named boxNoArgs( ), boxString( ), and boxNumberNumber( ). Each pseudo-
constructor's name indicates the number and datatype of the parameters it accepts (e.g.,
boxNumberNumber( ) defines two arguments of type Number
class Box
{
if (arguments.length == 0)
{
boxNoArgs( );
boxString(a1);
}
else if (typeof a1 == "number" && typeof a2 == "number")
{
boxNumberNumber(a1, a2);
else
{
if (arguments.caller != Box)
{
return;
width = 1;
height = 1;
if (arguments.caller != Box)
{
return;
if (size == "large")
{
width = 100;
height = 100;
}
else if (size == "small")
{
width = 10;
height = 10;
}
else
{
if (arguments.caller != Box)
{
return;
}
width = w;
height = h;
trace(b1.width); // Displays: 1
trace(b3.width); // Displays: 25