简体   繁体   中英

AS3 using base class object to create instance of extended class

I have a custom class that extends MovieClip . The idea is that it allows for storing extra variables and information about the MovieClip .

public class MapObject extends MovieClip
{
    private var cellX:int;
    private var cellY:int;

    public function MapObject()
    {
    }
 }

I have several MovieClips (.swf files) that I load at runtime. The problem is, how can I make these MovieClip objects actually become MapObject objects?

I've tried :

var mapObject:MapObject = myMovieClip as MapObject;

but it gives null

PS. I know you can add variables dynamically to MovieClips, but I don't really want to do that.

You can't change the class hierarchy without changing the code. You would have to go in each class definitions to change the parent class to MapObject instead of MovieClip .

There is an easy and clean solution which consists in using a decorator:

public class MapObject {

    private var mc:MovieClip;
    private var cellX:int;
    private var cellY:int;

    public class MapObject(mc:MovieClip) {
        this.mc = mc;
    }

    public function get movieClip():MovieClip {
        return mc;
    }
}
...

var wrapper:MapObject = new MapObject(new MyMovieClip());
...

container.addChild(wrapper.movieClip);

It's a wrapper that takes an instance of another class (in your case MovieClip) to add functionality. It's very powerful because you don't have to go and change each of your subclasses any time you change MapObject . This principle is called composition over inheritance .

In your case, all methods and properties of MovieClip are public so you would just write mc.play() instead of this.play() .

See the details about the Decorator design pattern .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM