Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
560 views
in Technique[技术] by (71.8m points)

actionscript 3 - Flash AS3 Global Variables?

HI i have a main class

//main.as

package {
    public class main {
        public var testGlobal:string = "testValue";

    }
}


//pop.as

package {
    public class pop {
        function pop():void {
            trace("testGloabl from main.as" + testGlobal);
        }
    }
}

How can i get the testGlobal value on pop.as width out using a main class Object. Is there any method of Global variables??

How to use global variables in AS3 .

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If you absolutely positively have to have a global variable in as3, you could always create a file in the top-level of your source folder like this:

MULTIPLIER.as

package
{
    public var MULTIPLIER:int = 3;
}

Then, whenever you need your multiplier you could reference wherever you need it like this:

DoSomeMultiplying.as

package multiplying
{
    public class DoSomeMultiplying
    {
        public function multiplyMe(n:int):int
        {
            var m:int = n * MULTIPLIER;
            MULTIPLIER = m;
            return m;
        }
    }
}

However, I would strongly recommend that you do not do this! it is horribly bad practice, horribly slow and, well, just horrible!

But there it is, it is possible to create a global variable or constant in the default package to act as a global constant or variable.

Declaring Global Functions in AS3

Note that you can also create global functions in the same way, and you don't need to use an import statement for (similar to the built-in trace function):

greet.as

package {
  public function greet():String { return "Hello World" }
}

Similar to the global variable, this global function is accessible from anywhere without an import statement:

package bar {
    public class foo
    {
        public function foo():void
        {
            trace("New foo says: "+greet()+", no import necessary");
            // New foo says: Hello World, no import necessary
        }
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.8k users

...