
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
Casting
|
45
Alternatively, we can cast the value to the desired type (casting is covered next, so if
it’s new to you, you may want to skip ahead for now). For example, the following
code casts
someValue to the TextField class so that it can be stored in the variable tf,
whose type is TextField:
var tf:TextField = TextField(someValue);
In ActionScript 2.0, casting data to a datatype always succeeds at compile time. That
is, the preceding code convinces the compiler that whatever the actual type of
someValue, it should be treated as a legitimate TextField object. In reality, the cast
operation may fail at runtime, but we’re talking only about compile-time type check-
ing here.
Once again, do not take either of these techniques for bypassing compile-time type
checking lightly!
It’s considered extremely bad form to add a new property (i.e., one not
defined by the object’s class) to a single object instance. It can also be
dangerous to cast an object to a class if the object is not actually an
instance of that class.
You may fool the compiler but, as we’ll learn next, at runtime you can easily end up
with a
null reference instead of the object you thought you cast. In the vast majority
of cases, you should not circumvent the type checking system. (However, as dis-
cussed in the next section, casting ...