MACROMEDIA FLASH 8-LEARNING ACTIONSCRIPT 2.0 IN FLASH Manual page 111

Learning actionscript 2.0 in flash
Table of Contents

Advertisement

About casting objects
The syntax for casting is
type of the item is
type
if the cast fails at runtime (this occurs in files published for Flash Player 7 or later; files
null
published for Flash Player 6 do not have runtime support for failed casts). If the cast succeeds,
the function call returns the original object. However, the compiler cannot determine whether
a cast will fail at runtime and won't generate compile-time errors in those cases.
The following code shows an example:
// Both the Cat and Dog classes are subclasses of the Animal class
function bark(myAnimal:Animal) {
var foo:Dog = Dog(myAnimal);
foo.bark();
}
var curAnimal:Animal = new Dog();
bark(curAnimal); // Will work
curAnimal = new Cat();
bark(curAnimal); // Won't work
In this example, you asserted to the compiler that
compiler assumes that
that the cast will fail (that is, that you tried to cast a Cat object to an Animal type), so no
compile-time error occurs. However, if you include a check in your script to make sure that
the cast succeeds, you can find casting errors at runtime, as shown in the following example.
function bark(myAnimal:Animal) {
var foo:Dog = Dog(myAnimal);
if (foo) {
foo.bark();
}
}
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 cast succeeds. If not, the cast
fails.
Casting to null or undefined returns undefined.
You can't override primitive data types that have a corresponding global conversion function
with a cast operator of the same name. This is because the global conversion functions have
precedence over the cast operators. For example, you can't cast to Array because the
conversion function takes precedence over the cast operator.
, where you want the compiler to behave as if the data
type(item)
. Casting is essentially a function call, and the function call returns
; is a legal statement. However, the compiler doesn't know
foo.bark()
is a Dog object, and therefore the
foo
Array()
About casting
111

Hide quick links:

Advertisement

Table of Contents
loading
Need help?

Need help?

Do you have a question about the FLASH 8-LEARNING ACTIONSCRIPT 2.0 IN FLASH and is the answer not in the manual?

This manual is also suitable for:

Flash 8

Table of Contents