Type Casting and the as Operator
ActionScript lets you change the assigned type of an object to other compatible types when needed. This is called casting. Both ActionScript 2 and 3 support casting using type(object) syntax. For example, if your custom class object was assigned to a variable typed as an object, you can reassign typing for that object by casting it to have a type of your custom class thereby letting Flash know what methods and properties exactly are available to that object
ActionScript Code:
var obj:Object = getMyCustomObject();
vay customObj:MyClass = MyClass(obj);
ActionScript 3 introduces a new operator for casting, the as operator. The as operator replaces casting using type(object) in ActionScript 2 with a syntax of object as type.
ActionScript Code:
var obj:Object = getMyCustomObject();
vay customObj:MyClass = obj as MyClass;
The as operator works much like casting in ActionScript 2. If the conversion can't be made, the result of the cast is null. Otherwise, the object being cast is returned and assigned a type of the type used.
ActionScript 3 still supports type(object) casting, but the behavior is a little different now. Instead of returning null for failed casting, a TypeError is thrown. Failure occurs when you try to cast an object into an incompatible type such as trying to cast one object into a type it is not associated with or inherits from.
Note: ActionScript also has global conversion functions in that work in the style of Class(object) which have precedence over type(object) casting. These include String(), Number(), and Array(), etc. These don't cast so much as actually convert one object into another (where applicable). Because these have precedence over type(object) casting, its preferred that the as operator be used when casting objects to different data types.

0 评论:
发表评论