访问 AS3 中的 Document 类 [英] Accessing the Document class in AS3

查看:30
本文介绍了访问 AS3 中的 Document 类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

实例化类如何访问文档类?

即使在我使用 Flash 中的属性栏命名文档类后,尝试从其他类访问它通常也会失败,说试图访问未定义的属性...em>

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...

一种解决方案总是将 Document 类强制转换为自身! 例如.

One solution is always casting the Document class to itself! 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();
   }
}

推荐答案

你可以为你的文档类使用单例(Main,在你的例子中),它允许你从任何地方访问实例.

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...
}

然后你像这样访问 Main 实例:

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.

这篇关于访问 AS3 中的 Document 类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆