2007年5月10日星期四

is Operator (vs instanceof)

The is operator (is operator) is a new keyword that lets you check to see if an instance is of a certain object type. This works for ActionScript 3 class instances checked against class types as well as interfaces. Ex:

ActionScript Code:

var mySprite:Sprite = new Sprite();
trace(mySprite is Sprite); // true
trace(mySprite is DisplayObject); // true
trace(mySprite is IEventDispatcher); // true


The is operator is a replacement for instanceof (instanceof operator) from ActionScript 1 and 2. The is operator, however, is specific to AS3 classes and is used to check the inheritance specific to those classes. This will not work on dynamic classes created with AS1-style constructor functions. In that situation, you would use instanceof since instanceof checks the prototype chain of an instance as opposed to class inheritance (which is does). Because an AS3 class's class inheritance is mirrored in its prototype chain, this means that instanceof will also work for AS3 classes, though is is prefered then (and less typing!).

ActionScript Code:

var mySprite:Sprite = new Sprite();
trace(mySprite instanceof Sprite); // true
trace(mySprite instanceof DisplayObject); // true
trace(mySprite instanceof IEventDispatcher); // false - not in prototype chain

ActionScript Code:

var AS1StyleClass:Function = function(){}
AS1StyleClass.
prototype = new MovieClip();

var as1Instance:* = new AS1StyleClass();
trace(as1Instance instanceof AS1StyleClass); // true
trace(as1Instance instanceof MovieClip); // true
trace(as1Instance is AS1StyleClass); // true
trace(as1Instance is MovieClip); // false - cant see prototype chain

0 评论: