ActionScript operator as
does anybody have a good explanation of the as operator?
On one hand it seems to me, that it is often better to use as instead of instantiating a new object.
But then there are situations, when this operator let's me down. For example when loading a text file in XML format through an URLLoader:
private function completeHandler(event:Event):void {
var loader:URLLoader = URL开发者_开发百科Loader(event.target);
trace("completeHandler: " + loader.data);
var x:XML = new XML(loader.data);
trace("x=" + x);
}
Why do I have to use a constructor here? Why can't I say var x:XML = loader.data as XML; and save some memory?
Thank you for any insights! Alex
as
evaluates whether a variable's type is a super class or subclass of another class. It does not create a new object. The difference to is
being that while is
returns a Boolean value, as
returns either an object of the desired type, or null
. It is used for type casts.
See the ActionScript documentation.
A typical use case would be using a MovieClip on the stage, which is retrieved by instance name:
// This will not compile:
var d:DisplayObject = stage.getChildByName ("instance1");
d.gotoAndPlay (2);
// This will play the MovieClip from frame 2
var m : MovieClip = stage.getChildByName ("instance1") as MovieClip;
m.gotoAndPlay (2);
stage.getChildByName()
always returns a DisplayObject, regardless if it's really a MovieClip, Sprite, Button, etc. So if you want to use any of class MovieClip's methods, you need to type cast to MovieClip first. This does not, however, create a new MovieClip but simply ensures that you are using the correct type.
精彩评论