Some of you will probably know the ‘as’-keyword. If not, a short explanation:
The ‘as’-keyword is used to cast an object to another one. (Well it’s not exactly ‘casting’, if someone feels like explaining the difference between casting with the ‘as’-keyword or by using the class constructor, please go ahead in the comment below!).
To make it more concrete, here is an example:
bart as Person
Where ‘bart’ is the variable and ‘Person’ the class you want the variable to cast to.
Now, the trouble starts when you want to use this keyword in combination with other operators.
Why? I hear you asking. Well: the ‘as’-keyword has a lower priority than i.e. the concatenation operator (+) in ActionScript.
To show you in an example:
trace("Result: " + bart as Person); // The output will look like: "null"Hu? Yes. It actually concatinates “Result: ” and bart first and than casts the whole thing to a Person object.
The fix is easy:
trace("Result: " + (bart as Person));
March 19, 2009
Well, casting like this Person(Bart) is syntax back from as2 (which still works in as3), and casting with ‘as’ is something new introduced in as3. Basicly both do the same thing; typecast an object but Person(Bart) throws a TypeError if it cannot cast Bart to the Person type where as just returns null.