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:
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:
You’re writing code that uses the object in
upState. upState is defined asDisplayObjectand allDisplayObjectdon’t have atextColorproperty, so it has to give you an error.upStateis allowed to actually contain anything that is aDisplayObjector a subclass ofDisplayObjectlike aTextField.You can tell the compiler that you know for sure it’s a
TextFieldby casting it.There is another form of casting using the
askeyword which will return the object, typed as specified, ornull. You want to use this keyword to test if an object is a certain type and then conditionally use it (via a!= nullcheck).