开发者

Actionscript 3 - Assign global variables inside function

I have an AS3 function that runs when a URLRequest fails. I need to be able to use this function to assign global variables that I can then check against using other functions. How do I assign global variables inside of a function?

Thanks!

Edit:This is the variable (soundFile2Exist) I am trying to get outside of my function:

function onIOError(e:IOErrorEvent):void 
{

    var soundFile2exist = null;
    trace (soundFile2exist);
}

I am not using my code inside of a packge. Is there still a way to do this?

function playMusic(ev开发者_如何学JAVAt:MouseEvent):void
{
    channel = myMusic.play(songPosition);
    if (soundFile2exist != null) {
          channel2 = myMusic2.play(channel.position);
    }
    myTimer.start();
    btnPlay.mouseEnabled = false;
    trace (soundFile2exist);

}


If your code is "not in a package" (like in a frame script on a timeline), any variables you declare on the same level, same scope, as your functions will be accessible to the functions in that scope, so you could do something in the lines of this:

var soundFile2exist;

function onIOError(e:IOErrorEvent):void {
   soundFile2exist = null;
}

function otherFunction():void {
   trace (soundFile2exist);
}

In other situations, static variables of a class can be used in place of global variables.


The most common approach is to create a Singleton class which you can then reference from anywhere. This basically sets up a class where the only way to get access to an instance of that class is via a controlled static method that returns one and only one instance. So whenever you say MySingleton.getInstance() you always end up with the same object.

Grant Skinner has a quick writeup of how to implement a Singleton in AS3: http://gskinner.com/blog/archives/2006/07/as3_singletons.html

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜