stian
stian

Reputation: 1987

How to overcome implicit coercion? (Casting to custom class)

I have a class that extends the Sprite class (which makes it a DisplayObject), and I have added it as a child to stage for visualization: stage.addChild(object).

I would like to make an alteration to this object by taking a reference to it out of the stage and work with it (stage.getChildByName(object)), but now the object I receive from the stage is of type DisplayObject. If I am sure this object received from the stage is of my class - can I cast the displayObject to my class somehow?

Upvotes: 0

Views: 68

Answers (1)

BadFeelingAboutThis
BadFeelingAboutThis

Reputation: 14406

Casting is done 2 ways in AS3.

You could do a proper cast:

MyClass(object)

This will throw an error if the cast fails.

You could also use the as keyword:

object as MyClass;

This will return null if the cast fails.


You need to be aware, that getChildByName does not accept an object, but a string (that corresponds to the .name (or instance name) value of a display object. If you already have a reference to object, then there is no need look it up from stage.getChildByName

Upvotes: 2

Related Questions