在AS3中使变量全局化?

时间:2015-03-21 16:01:29

标签: actionscript-3

如何将此变量设为全局 - 可以从源路径中的任何位置/任何位置调用?

public var newLine:String = "\n";

public function get newLine():String {
    return "\n";
}
P.S:我正在阅读清洁代码书。在第11章:系统:分离构建系统与使用它:分离主要,它说Notice the direction of the dependency arrows crossing the barrier between 'main' and the application. They all go one direction, pointing away from 'main'. This means that the application has no knowledge of main or of the construction process.如果我理解正确,我不应该把变量放在Main类中,我应该吗?

2 个答案:

答案 0 :(得分:0)

有两种创建全局变量的方法:

  1. 使用静态变量。在static之前添加var

    public static var newLine:String = "\n";
    

    因此,您可以通过输入以下内容来解决此变量:

    YourClass.newLine
    
  2. 使用Singletone模式。

    package
    {
        public class Singleton
        {
            private static var instance:Singleton;
    
            public var newLine:String = "\n";
    
            public function Singleton()
            {
                if (instance)
                    throw new Error("Use getInstance()");
                instance = this;
            }
    
            public static function getInstance():Singleton
            {
                if (!instance)
                    new Singleton();
                return instance;
            }
        }
    }
    

    因此,您可以通过输入以下内容来解决newLine变量:

    Singleton.getInstance().newLine
    

答案 1 :(得分:0)

还有一种方法:

package { 
    public function get newline():String {
        return "\n";
    }
}

用法:

var myText:String = "Hello" + newline;
相关问题