views:

193

answers:

1

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 http://stackoverflow.com/questions/2158886/as3-global-var-of-type-simplebutton-changes-to-displayobject-for-unknown-reason. I'm posting this because its more focused and deals with a single aspect of the broader issue.

+2  A: 

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;
}
Sam