User Guide

60 ActionScript Language and Syntax
The is operator examines the proper inheritance hierarchy and can be used to check not only
whether an object is an instance of a particular class, but also whether an object is an instance
of a class that implements a particular interface. The following example creates an instance of
the Sprite class named
mySprite and uses the is operator to test whether mySprite is an
instance of the Sprite and DisplayObject classes, and whether it implements the
IEventDispatcher interface:
var mySprite:Sprite = new Sprite();
trace(mySprite is Sprite); // true
trace(mySprite is DisplayObject); // true
trace(mySprite is IEventDispatcher); // true
The is operator checks the inheritance hierarchy and properly reports that mySprite is
compatible with the Sprite and DisplayObject classes (the Sprite class is a subclass of the
DisplayObject class). The
is operator also checks whether mySprite inherits from any classes
that implement the IEventDispatcher interface. Because the Sprite class inherits from the
EventDispatcher class, which implements the IEventDispatcher interface, the
is operator
correctly reports that
mySprite implements the same interface.
The following example shows the same tests from the previous example, but with
instanceof
instead of the
is operator. The instanceof operator correctly identifies that mySprite is an
instance of Sprite or DisplayObject, but it returns
false when used to test whether mySprite
implements the IEventDispatcher interface.
trace(mySprite instanceof Sprite); // true
trace(mySprite instanceof DisplayObject); // true
trace(mySprite instanceof IEventDispatcher); // false
The as operator
The as operator, which is new in ActionScript 3.0, also allows you to check whether an
expression is a member of a given data type. Unlike the
is operator, however, the as operator
does not return a Boolean value. Rather, the
as operator returns the value of the expression
instead of
true, and null instead of false. The following example shows the results of using
the
as operator instead of the is operator in the simple case of checking whether a Sprite
instance is a member of the DisplayObject, IEventDispatcher, and Number data types.
var mySprite:Sprite = new Sprite();
trace(mySprite as Sprite); // [object Sprite]
trace(mySprite as DisplayObject); // [object Sprite]
trace(mySprite as IEventDispatcher); // [object Sprite]
trace(mySprite as Number); // null
When you use the as operator, the operand on the right must be a data type. An attempt to
use an expression other than a data type as the operand on the right will result in an error.