问题描述
我期待一些讽刺,但到底是什么.我搜索了 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.
推荐答案
已经有几个很好的答案.我只想指出 YOU CAN
在 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 posterI 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>
运行应用程序,跟踪确实以正确的bla"值显示了两次.
Run the app and the trace does indeed show up twice with the correct 'bla' value.
这篇关于如何在 actionscript 中声明一个全局变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!