简体   繁体   English

访问AS3中的Document类

[英]Accessing the Document class in AS3

How can instantiated classes access the Document class? 实例化类如何访问Document类?

Even after I name the Document class using the Properties bar in Flash, attempting to access it from other classes usually fails, saying "attempting to access an undefined property... 即使我使用Flash中的属性栏命名Document类 ,尝试从其他类访问它通常也会失败,说“尝试访问未定义的属性...

One solution is always casting the Document class to itself! 一种解决方案总是将Document类转换为自身! eg. 例如。

Main(Main).globalMethod();

But sometimes even this stellar gotcha fails, and then there's usually no way out, apart from the obvious! 但有时甚至这个恒星失败了,然后通常没有出路,除了显而易见的!

class Other{

   var parentClass:Main;
   public function Other(parent:Main){
       parentClass = parent;            // pointer to the Main class in a local var!

       Main(parentClass).globalMethod();
   }
}

You can use a singleton for your document class ( Main , in your example), which allows you to access the instance from anywhere. 您可以为文档类使用单例(在示例中为Main ),这允许您从任何位置访问实例。

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: 然后你像这样访问Main实例:

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. 如果要调用文档类中的方法,则必须始终将Main中的引用传递给要调用其方法的任何其他类/对象。 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. 更面向对象的方法是从其他类(其他)调度事件,以便Main类监听并调用适当的方法。

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 ); 如果您不关心保持良好的OOP结构并希望从已添加到显示列表的显示对象访问文档类,您可以尝试类似: 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. 在这方面,文档类与任何其他类没有什么不同。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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