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 pseudoconstructor's name indicates the number and datatype of the parameters it accepts (e.g.,
boxNumberNumber( ) defines two arguments of type Number
if (arguments.length == 0)
{
boxNoArgs( );
}
else if (typeof a1 == "string")
{
boxString(a1);
}
if (arguments.caller != Box)
{
return;
width = w;
height = h;
}
}