访问在AS3文档类文档

2023-09-08 12:23:50 作者:江南樱雨﹍断桥殇

如何才能实例化的类的访问文档类?

即使我的名字的文件类使用Flash中的属性栏,试图从其它类通常无法访问,说的尝试访问未定义的属性...

解决方案之一是永远的铸造文档类本身!如:

 主(主).globalMethod();
 

但有时即使是这个恒星的疑难杂症失败,那么通常没有出路,除了显而易见!

 类其他{

   VAR父类:主;
   公共职能其他(父:主){
       父类=父母; //指向主类的局部变量!

       主(父类).globalMethod();
   }
}
 

解决方案 AS3基础教程 第65课 文档类

您可以使用一个单独的文档类(,在你的例子),它允许你从任何位置访问该实例。

 公共类主要扩展Sprite {
    私人静止无功_instance:主;
    公共静态函数获得实例():主要{返回_instance; }

    公共函数main(){
        _instance =这一点;
       // 等等...
    }

    // 等等...
}
 

然后你访问实例是这样的:

 公共类其他{
    公共职能其他(){
        Main.instance.usefulInstanceMethod();
    }
}
 

文档类是pretty的好选择单例模式,因为通常应该只有可用实例。

How can instantiated classes access the Document class?

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

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();
   }
}

解决方案

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.