AS3: cast or “as”?

前端 未结 8 1700
天命终不由人
天命终不由人 2020-11-30 10:25

Is there any difference of use, efficiency or background technique between

var mc:MovieClip = MovieClip(getChildByName(\"mc\"));

and

<
相关标签:
8条回答
  • 2020-11-30 11:00

    It is best practice to use the as keyword.

    as has the advantage of not throwing an RTE (run-time error). For example, say you have a class Dog that cannot be cast into a MovieClip; this code will throw an RTE:

    var dog:Dog = new Dog();
    var mc:MovieClip = MovieClip(Dog);
    

    TypeError: Error #1034: Type Coercion failed: cannot convert Dog to MovieClip.

    In order for you to make this code "safe" you would have to encompass the cast in a try/catch block.

    On the other hand, as would be safer because it simply returns null if the conversion fails and then you can check for the errors yourself without using a try/catch block:

    var dog:Dog = new Dog();
    var mc:MovieClip = Dog as MovieClip;
    if (mc) 
        //conversion succeeded
    else
        //conversion failed
    
    0 讨论(0)
  • 2020-11-30 11:00

    (cast) and "as" are two completely different things. While 'as' simply tells the compiler to interpret an object as if it were of the given type (which only works on same or subclasses or numeric/string conversions) , the (cast) tries to use a static conversion function of the target class. Which may fail (throwing an error) or return a new instance of the target class (no longer the same object). This explains not only the speed differences but also the behavior on the Error event, as described by Alejandro P.S.

    The implications are clear: 'as' is to be used if the class of an object is known to the coder but not to the compiler (because obfuscated by an interface that only names a superclass or '*'). An 'is' check before or a null check after (faster) is recommended if the assumed type (or a type compatible to auto-coercion) cannot be 100% assured.

    (cast) is to be used if there has to be an actual conversion of an object into another class (if possible at all).

    0 讨论(0)
提交回复
热议问题