Accessing the Document class in AS3

五迷三道 提交于 2019-11-30 08:26:17

You can use a singleton for your document class (Main, in your example), which allows you to access the instance from anywhere.

public class Main extends Sprite {
    private static var _instance:Main;
    public static function get instance():Main { return _instance; }

    public function Main() {
        _instance = this;
       // etc...
    }

    // etc...
}

Then you access the Main instance like this:

public class Other {
    public function Other() {
        Main.instance.usefulInstanceMethod();
    }
}

The document class is a pretty good candidate for the singleton pattern, because generally there should only be instance available.

The document class is not inherently a globally accessible object. If you want to call methods that are in the document class, you'll always have to pass a reference from Main to any other classes/objects that want to call its methods. A more object oriented approach would be to dispatch events from your other classes (Other) for the Main class to listen to and call an appropriate method in itself.

If you are unconcerned about keeping a good OOP structure and want to access the document class from a display object that has been added to the display list you could try something like: stage.getChildAt( 0 );

Just a side note, but the shortest answer to this question is: the same way any class access any other class. That is, with either a direct reference or a static exposure. The document class is no different from any other class in this regard.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!