AS3.0 Type Casting, what is the deal?
Friday, October 31st, 2008I recently had someone ask me the difference between using:
MovieClip( object );
// and
object as MovieClip
I ran some tests to show the example of what actually happens and here you go:
var o:Object = "test"; trace( 'MovieClip: ' + o as MovieClip ); // displays: null trace( 'Array: ' + o as Array ); // displays: null trace( 'Object: ' +o as Object ); // displays: Object: test trace( 'String: ' +o as String ); // displays: String: test trace( 'Boolean: ' + Boolean(o) ); // displays: Boolean: true trace ( 'MovieClip: ' +MovieClip ( o ) ); // generates a TypeError
Using the MovieClip( x ) or Boolean( x ) method tries to do a Type Conversion. The Boolean succeeds because it finds that there IS a value available and converts to true. If the value were NULL, it would read false. MovieClip fails because the type just does not match.
When you cast using “as”, it seems to attempt a Try/Catch basically. It will return a null if unavailable, but will not crash your application.
Because a Sprite is below a MovieClip in the inheritance chain, it cannot cast it’s way up.
Worthy of noting: MovieClips are dynamic classes. Sprites are not. Only dynamic classes can receive custom (dynamic) variables. This means you can assign whatever variable you want to a MovieClip, but do not try that with a Sprite.
var mc:MovieClip = new MovieClip(); mc.customVar = 'matt'; trace(mc.customVar); // traces: matt var newmc:MovieClip = MovieClip(mc); trace(newmc.customVar); // traces: matt var newsp:Sprite = Sprite(mc); trace(newsp.customVar); // undefined property error
If you try to set a Sprite, then cast it as a MovieClip, you will get a Type Coercion error.
var sp:Sprite = new Sprite(); var mc:MovieClip = MovieClip(sp); // error trace(mc);
What does it all mean?
Type Casting is a one-way trip down the inheritance chain. Your basic MovieClip inherits like this:
MovieClip -> Sprite -> DisplayObjectContainer -> InteractiveObject -> DisplayObject -> EventDispatcher -> Object
This is why a MovieClip can cast down to a Sprite, but a Sprite cannot cast up. You can take something away (cast down)… but you cannot create something from nothing (cast up).







