Thursday, February 7, 2013

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 and IEventDispatcher data types.
var mySprite:Sprite = new Sprite();
trace (mySprite as Sprite);                         // output: [object Sprite]
trace (mySprite as DisplayObject);            // output: [object Sprite]
trace (mySprite as IEventDispatcher);       // output: [object Sprite]
The right-hand operand used with the as operator must be a data type. An attempt to use an expression other than a data type as the right-hand operand will result in an error.

A common usage of the as operator is to assign the result of an as operation to a variable of the same type. For example, the following code takes a zip code from an online form that is a String value and assigns the result of an as operation to a variable of type Number. The num variable is assigned the numeric value 94103 because Flash Player converts the string to a numeric value per the implicit conversion rules of ActionScript 3.0.
var zipCode:String = "94103"
var num:Number = zipCode as Number;
trace(num); // output: 94103
The main benefit of using the as operator is that it should guarantee that the result of the as operation will either be the value of the left-hand expression or null. In the zip code example, however, the variable num is a primitive data type, and none of the primitive data types contain the value null. In these situations, Flash Player converts the value null into the default value of primitive data type. In the case of the Number data type, the default value is NaN. For example, if the zipCode variable in the previous example is a nine digit zip code with a hyphen, the conversion will fail. The as operator attempts to return null, because the implicit conversion failed, but the num variable cannot accept a null value, so the default value of the Number data type, NaN, is used instead.
var zipCode:String = "94103-1734"
var num:Number = zipCode as Number;
trace(num); // output: NaN

Programming Actionscript 3. Powered by Blogger.