开发者

AS3: Why does datatype automatically change from TextField to DisplayObject on its own?

开发者 https://www.devze.com 2022-12-18 18:04 出处:网络
What\'s happening in this simple piece of AS3 code? Why does my object change from TextField to the more generic DisplayObject?

What's happening in this simple piece of AS3 code? Why does my object change from TextField to the more generic DisplayObject?

public class Menu extends MovieClip
     {
      private var active_button:SimpleButton;

      public function Menu() 
      {
       active_button = SimpleButton( menu_list.getChildAt( 0 )); // ignore menu_list. it's just a collection of SimpleButtons
       trace( active_button.upState ); // [object TextField]
                // ** What's occuring here that makes active_button.upState no longer a TextField? **
       active_button.upState.textColor = 0x000000; // "1119: Access of possibly undefined property textColor through a reference with static type flash.display:DisplayObject." 

This question is simliar to AS3: global var of type SimpleButton 开发者_如何学运维changes to DisplayObject for unknown reason, won't let me access .upState.textColor!. I'm posting this because its more focused and deals with a single aspect of the broader issue.


You're seeing the difference between compile time and run-time type. In this code:

trace( active_button.upState ); // [object TextField]

You're passing the object to trace and trace is going to show the actual object type that exists at run-time.

However, in this case:

active_button.upState.textColor = 0x000000;

You're writing code that uses the object in upState. upState is defined as DisplayObject and all DisplayObject don't have a textColor property, so it has to give you an error. upState is allowed to actually contain anything that is a DisplayObject or a subclass of DisplayObject like a TextField.

You can tell the compiler that you know for sure it's a TextField by casting it.

TextField(active_button.upState).textColor = 0x000000;

There is another form of casting using the as keyword which will return the object, typed as specified, or null. You want to use this keyword to test if an object is a certain type and then conditionally use it (via a != null check).

var textField:TextField = active_button.upState as TextField;
if (textField != null) {
    textField.textColor = 0;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消