How does one declare a global variable in actionsc

2019-04-17 12:01发布

问题:

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.

回答1:

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";
}

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:

In the root directory:

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

A test class:

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

And the test application:

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



回答2:

There are no global variables in as3. But static variables can be accessed without creating an instance of the class, so they can be used as global variables.

package 
{
     class MyClass
     {
         // ...
         public static var myStaticVar: Number;
         // ...
     }
}

Then any where in your program, you can access the variable myStaticVar like follows:

MyClass.myStaticVar = 5;
// ...
var value:Number = MyClass.myStaticVar;


回答3:

Global to what?

If you want to declare a variable which is "global" to a class; you can just use any variable:

public var myClassGlobal : Object = new Object();

This variable will be accessible anywhere inside the class; and because I made it public it is also available to any classes that can access an instance of that class. You would access it like this:

trace(myClassInstance.myClassGlobal);

If you want to declare a variable which is "global" to a Flex Application, you can declare a variable in the main application file:

public var myFlexApplicationGlobal :Object = new Object():

You can access this value anywhere in your code using the FlexGlobals.topLevelApplication. Something like this:

trace((FlexGlobals.topLevelApplication as myMainApplicationFile).myFlexApplicationGlobal);

An approach like this is generally considered an encapsulation no-no; because it gives your classes a dependency on the main application file and minimizes re-use. That is generally something we try to avoid.

You could create a static variable and access it anywhere using the class. Static variables are not tied to an instance of the class:

public static var myStaticGlobal :Object = new Object():

You would access it like this:

trace(MyClassWithStaticVariable.myStaticGlobal);

You could also create a Singleton class with your global variables and use a framework, such as Swiz or RobotLegs to inject that class into the classes that need it. A quick google search should reveal you information on creating Singletons in Flex; and there is plenty of discussion for and against Singletons in the scope of the greater programming community..



回答4:

package com.appcloud9.utils
{
    public class GlobalReference
    {
        public static function get global() : Object
        {
            var getGlobal : Function = function() : Object
            {
                return this;
            };
            return getGlobal();
        }
    }
}

/*-|-||-|-||-|-||-  usage examples  -||-|-||-|-||-
 * the examples below focus on giving global access to the main Stage instance
 * but anything added to the global object ( which always exists no matter what )
 * is accessible via the same mechanisms
*/

// global stage reference added in main document class upon Event.EXIT_FRAME :
GlobalReference.global.stage = stage;

// later in a closure
var signalLightsOut = new Signal();
signalLightsOut.add( function() : void
{
    /* because the [ object global ] truly is 'global' all closures have
     * direct access to any properties added to it ( it is a dynamic class )
    */ 
    trace( stage );                        // [object Stage]
} );

// later in a constructor - before the class has a stage of it's own
public function MyConstructor()
{
    trace( stage );                        // null
    trace( GlobalReference.global.stage ); // [object Stage]
}


回答5:

From within a method closure the keyword this returns a reference to the 'global' object.
Below are some interesting results when inspecting this from inside a method closure.

trace( this );    // outputs : [object global]

trace( flash.utils.describeType( this ) );

/* outputs :
description:
<type name="global" base="Object" isDynamic="true" isFinal="true" isStatic="false">
  <extendsClass type="Object"/>
  <constant name="Boolean" type="Boolean"/>
  <constant name="Namespace" type="Namespace"/>
  <constant name="undefined" type="*"/>
  <constant name="Number" type="Number"/>
  <constant name="USE_ITRAITS" type="uint" uri="avmplus"/>
  <constant name="Vector" type="__AS3__.vec::Vector" uri="__AS3__.vec"/>
  <constant name="uint" type="uint"/>
  <constant name="Infinity" type="Number"/>
  <constant name="int" type="int"/>
  <constant name="String" type="String"/>
  <constant name="Object" type="Object"/>
  <constant name="HIDE_NSURI_METHODS" type="uint" uri="avmplus"/>
  <constant name="INCLUDE_BASES" type="uint" uri="avmplus"/>
  <constant name="Array" type="Array"/>
  <constant name="INCLUDE_VARIABLES" type="uint" uri="avmplus"/>
  <constant name="INCLUDE_ACCESSORS" type="uint" uri="avmplus"/>
  <constant name="INCLUDE_INTERFACES" type="uint" uri="avmplus"/>
  <constant name="INCLUDE_METHODS" type="uint" uri="avmplus"/>
  <constant name="INCLUDE_METADATA" type="uint" uri="avmplus"/>
  <constant name="INCLUDE_CONSTRUCTOR" type="uint" uri="avmplus"/>
  <constant name="INCLUDE_TRAITS" type="uint" uri="avmplus"/>
  <constant name="Class" type="Class"/>
  <constant name="HIDE_OBJECT" type="uint" uri="avmplus"/>
  <constant name="FLASH10_FLAGS" type="uint" uri="avmplus"/>
  <constant name="AS3" type="*"/>
  <constant name="Function" type="Function"/>
  <constant name="NaN" type="Number"/>
  <method name="parseInt" declaredBy="global" returnType="Number">
    <parameter index="1" type="String" optional="true"/>
    <parameter index="2" type="int" optional="true"/>
  </method>
  <method name="parseFloat" declaredBy="global" returnType="Number">
    <parameter index="1" type="String" optional="true"/>
  </method>
  <method name="escape" declaredBy="global" returnType="String">
    <parameter index="1" type="String" optional="true"/>
  </method>
  <method name="unescape" declaredBy="global" returnType="String">
    <parameter index="1" type="String" optional="true"/>
  </method>
  <method name="isXMLName" declaredBy="global" returnType="Boolean">
    <parameter index="1" type="*" optional="true"/>
  </method>
  <method name="describeType" declaredBy="global" returnType="XML" uri="avmplus">
    <parameter index="1" type="*" optional="false"/>
    <parameter index="2" type="uint" optional="false"/>
  </method>
  <method name="getQualifiedClassName" declaredBy="global" returnType="String" uri="avmplus">
    <parameter index="1" type="*" optional="false"/>
  </method>
  <method name="getQualifiedSuperclassName" declaredBy="global" returnType="String" uri="avmplus">
    <parameter index="1" type="*" optional="false"/>
  </method>
  <method name="decodeURI" declaredBy="global" returnType="String">
    <parameter index="1" type="String" optional="true"/>
  </method>
  <method name="decodeURIComponent" declaredBy="global" returnType="String">
    <parameter index="1" type="String" optional="true"/>
  </method>
  <method name="encodeURI" declaredBy="global" returnType="String">
    <parameter index="1" type="String" optional="true"/>
  </method>
  <method name="encodeURIComponent" declaredBy="global" returnType="String">
    <parameter index="1" type="String" optional="true"/>
  </method>
  <method name="isNaN" declaredBy="global" returnType="Boolean">
    <parameter index="1" type="Number" optional="true"/>
  </method>
  <method name="isFinite" declaredBy="global" returnType="Boolean">
    <parameter index="1" type="Number" optional="true"/>
  </method>
</type>:
*/

description = flash.utils.describeType( Object( this ).constructor as Class );
trace( "description:\n" + description );

/* outputs :
<type name="Object" base="Class" isDynamic="true" isFinal="true" isStatic="true">
  <extendsClass type="Class"/>
  <extendsClass type="Object"/>
  <constant name="length" type="int"/>
  <accessor name="prototype" access="readonly" type="*" declaredBy="Class"/>
  <factory type="Object"/>
</type>:
*/