There seems to be some confusion amongst the community as to the details of casting objects to a class. There are two ways to do this:
1. Cast using the constructor… Constructor(obj);
2. Cast using the “as” operator… (obj as Constuctor);
There are subtle yet significant differences between these two approaches.
The first – passing a single argument to a class Constructor without using the “new” operator – will attempt to make conversions to the object and produce a valid instance of the class.
The second – using the “as” operator – will ask the compiler to walk up and down super and subclasses within the same hierarchy. It will not attempt to convert the object.
Here’s a simple e.g.,
[as3]var num:String = "1";
trace(Number(num)); // will output 1 – a valid Number object
trace(num as Number)); // will output null – no conversion as made[/as3]
Generally (as noted in my post about optimization here), using the “as” operator is faster (and IMO a little more elegant), but should be used only when the object to be cast shares a superclass with the constructor class. This is very handy when casting event.target or the DisplayObject returned by getChildAt as instances of ‘MyClass’.
When attempting to cast something that does not share a relationship, the Constructor(obj) method is required.
There’s a somewhat misleading warning in the CS compiler when passing multiple arguments to Array (without the ‘new’ keyword) that seems to suggest casting using ‘as’ is preferred – I’m not sure this is accurate.