The reason for this is that when you publish a file for ActionScript 1, Flash interprets a statement
such as
as slash syntax rather than as strict typing. (ActionScript 2.0
var x:String = "abc"
doesn't support slash syntax.) This behavior can result in an object that is assigned to a variable of
the wrong type, causing the compiler to let illegal method calls and undefined property references
pass through unreported.
Therefore, if you are implementing strict data typing, make sure you are publishing files for
ActionScript 2.0.
Casting objects
ActionScript 2.0 lets you cast one data type to another. The cast operator that Flash uses takes the
form of a function call and is concurrent with explicit coercion, as specified in the ECMA-262
Edition 4 proposal. Casting lets you assert that an object is of a certain type so that when type-
checking occurs, the compiler treats the object as having a set of properties that its initial type
does not contain. This can be useful, for example, when iterating over an array of objects that
might be of differing types.
In files published for Flash Player 7 or later, cast statements that fail at runtime return
. In
null
files published for Flash Player 6, no runtime support for failed casts is implemented.
The syntax for casting is
, where you want the compiler to behave as if the data type
type(item)
of
is
. Casting is essentially a function call, and the function call returns
if the cast
item
type
null
fails. If the cast succeeds, the function call returns the original object. However, the compiler
doesn't generate type mismatch errors when you cast items to data types that you created in
external class files, even if the cast fails at runtime.
// in Animal.as
class Animal {}
// in Dog.as
class Dog extends Animal { function bark (){} }
// in Cat.as
class Cat extends Animal { function meow (){} }
// in FLA file
var spot:Dog = new Dog();
var temp:Cat = Cat (spot);
// assert that a Dog object is of type Cat
temp.meow(); // doesn't do anything, but no compiler error either
In this situation, you asserted to the compiler that
is a Cat object, and, therefore, the
temp
compiler assumes that
is a legal statement. However, the compiler doesn't know
temp.meow()
that the cast will fail (that is, that you tried to cast a Dog object to a Cat type), so no compile-time
error occurs. If you include a check in your script to make sure that the cast succeeds, you can
find type mismatch errors at runtime.
var spot:Dog = new Dog();
var temp:Cat = Cat (spot);
trace(temp);
// displays null at runtime
You can cast an expression to an interface. If the expression is an object that implements the
interface or has a base class that implements the interface, the object is returned. If not,
null
is returned.
Assigning data types to elements
39
Need help?
Do you have a question about the FLASH MX 2004 - ACTIONSCRIPT and is the answer not in the manual?
Questions and answers