
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
Casting
|
51
following code attempts to cast an Object instance to the TextField type. In theory, the
cast should fail and return
null because the instance does not belong to the TextField
type. However, in Flash Player 6, the cast returns the Object instance:
var obj:Object = new Object( );
// When exported to Flash Player 6 format, displays: [object Object]
// (Would display null if exported to Flash Player 7 format)
trace(TextField(obj));
Never lie when you cast! It’s never sensible to use a cast to lie to the
compiler about the type of an object.
If you cast an object to an incompatible datatype, the compiler may be fooled, but
you still won’t be able to use the object as an instance of that datatype at runtime. As
we just learned, in Flash Player 7–format .swf files, a cast that fails returns the value
null at runtime, which will almost certainly break some aspect of your program:
var obj:Object = new Object( );
trace(TextField(obj)); // If exported to Flash Player 7 format,
// displays: null
You should perform only those casts you know to be valid.
If you cannot guarantee that a cast will succeed, you should first use
instanceof to check whether the cast will succeed at runtime before
attempting the cast operation.
For example, the following code checks the actual type of obj at runtime ...