Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 4

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

Example 4-5. Simulating overloaded constructors

class Box
{

public var width:Number;

public var height:Number;

public function Box (a1:Object, a2:Object)


{

if (arguments.length == 0)
{

boxNoArgs( );

else if (typeof a1 == "string")


{

boxString(a1);

}
else if (typeof a1 == "number" && typeof a2 == "number")
{

boxNumberNumber(a1, a2);

else
{

trace("Unexpected number of arguments passed to Box constructor.");

/** * No-argument constructor. */

private function boxNoArgs ( ):Void

if (arguments.caller != Box)
{

return;

width = 1;

height = 1;

/** * String constructor. */

private function boxString (size):Void


{

if (arguments.caller != Box)
{

return;

if (size == "large")
{

width = 100;

height = 100;

}
else if (size == "small")
{

width = 10;

height = 10;

}
else
{

trace("Invalid box size specified");

/** * Numeric constructor. */

private function boxNumberNumber (w, h):Void


{

if (arguments.caller != Box)
{

return;

}
width = w;

height = h;

// Usage: ***** NEED TO CALL FROM FLASH ****

var b1:Box = new Box( );

trace(b1.width); // Displays: 1

var b2:Box = new Box("large");

trace(b2.width); // Displays: 100

var b3:Box = new Box(25, 35);

trace(b3.width); // Displays: 25

You might also like