AS3: cast or “as”?

前端 未结 8 1697
天命终不由人
天命终不由人 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
    

提交回复
热议问题