怎样才能声明ActionScript中的全局变量 [英] How does one declare a global variable in actionscript

查看:415
本文介绍了怎样才能声明ActionScript中的全局变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我期待一些嘲讽但是什么。我已经搜查了动作参考页,似乎无法找到如何声明简单的全局变量。

i expect some sarcasm but what the heck. i have searched the actionscript reference page and can't seem to find how to declare simple global variable.

推荐答案

有几个很好的答案了。我只是想指出的是,可以创建AS3全局变量。只需创建一个文件,例如,在你的类文件夹的根目录MyGlobal.as:

There are a couple of good answers already. I just want to point out that YOU CAN create global variables in AS3. Just create a file, for example, MyGlobal.as in root of your classes folder:

package {
    public var MyGlobal:String = "bla";
}

您可以访问它作为 MyGlobal ,因为它是在最上面的包。这种技术可以在几个不那么破坏性方式使用。例如,你可以有一个全局常量,它类似于一个单身,但不是静态的将是一些类的只是一个实例:

And you can access it as MyGlobal because it is in the top most package. This technique can be used in several not so destructive ways. For example you can have a global constant which is similar to a singleton but instead of being static it will be just an instance of some class:

package {
    public const MySingleton:IMySingleton = new MySingletonImpl();
}


更新;没有从原来的海报 我从来没有听说过这个之前,让我组建了一个快速的示例:


Update; not from the original poster I had never heard of this before so I put together a quick sample:

在根目录下:

package
{
    public var MyGlobal:String = "bla";
}

一个测试类:

package com.flextras.stackOverflow
{
    public class MyGlobalTest
    {
        public function MyGlobalTest()
        {
            trace(MyGlobal);
        }
    }
}

和测试应用程序:

<?xml version="1.0" encoding="utf-8"?>
<s:WindowedApplication xmlns:fx="http://ns.adobe.com/mxml/2009" 
                       xmlns:s="library://ns.adobe.com/flex/spark" 
                       xmlns:mx="library://ns.adobe.com/flex/mx" initialize="windowedapplication1_initializeHandler(event)">
    <fx:Script>
        <![CDATA[
            import com.flextras.stackOverflow.MyGlobalTest;

            import mx.events.FlexEvent;

            protected function windowedapplication1_initializeHandler(event:FlexEvent):void
            {
                trace(MyGlobal);
                var a :MyGlobalTest = new MyGlobalTest();
            }

        ]]>
    </fx:Script>
    <fx:Declarations>
        <!-- Place non-visual elements (e.g., services, value objects) here -->
    </fx:Declarations>
</s:WindowedApplication>

运行应用程序并跟踪确实出现两次正确的喇嘛的价值。

Run the app and the trace does indeed show up twice with the correct 'bla' value.

这篇关于怎样才能声明ActionScript中的全局变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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