User Guide
Advanced Topics 245
The four overridden methods all use the AS3 namespace instead of the public attribute
because this example assumes that the compiler option
-as3 is set to true and the compiler
option
-es is set to false. These are the default settings for Adobe Flex Builder 2 and for
Adobe Flash CS3 Professional. For more information, see “The AS3 namespace” on page 147.
TypedArray constructor
The subclass constructor poses an interesting challenge because the constructor must accept a
list of arguments of arbitrary length. The challenge is how to pass the arguments on to the
superconstructor to create the array. If you pass the list of arguments as an array, the
superconstructor considers it a single argument of type Array and the resulting array is always
1 element long. The traditional way to handle pass-through argument lists is to use the
Function.apply() method, which takes an array of arguments as its second parameter but
converts it to a list of arguments when executing the function. Unfortunately, the
Function.apply() method cannot be used with constructors.
The only option left is to recreate the logic of the Array constructor in the TypedArray
constructor. The following code shows the algorithm used in the Array class constructor,
which you can reuse in your Array subclass constructor:
public dynamic class Array
{
public function Array(...args)
{
var n:uint = args.length
if (n == 1 && (args[0] is Number))
{
var dlen:Number = args[0];
var ulen:uint = dlen;
if (ulen != dlen)
{
throw new RangeError("Array index is not a 32-bit unsigned integer
("+dlen+")");
}
length = ulen;
}
else
{
length = n;
for (var i:int=0; i < n; i++)
TIP
If you are an advanced developer who prefers to use prototype inheritance, you can
make two minor changes to the TypedArray class to make it compile with the compiler
option -es set to true. First, remove all occurrences of the override attribute and
replace the AS3 namespace with the public attribute. Second, substitute
Array.prototype for all four occurrences of super.