By using AS3, should I declare variables globally or in a function only when they are needed?


I am working with URLLoader and URLRequest in this case.

I have two buttons. One listens for the mouse click event and then runs the following function (less code not applicable to this question):

function loadURL (e:MouseEvent):void {


    var myRequest:URLRequest=new URLRequest("*URL*");

    var myLoader:URLLoader = new URLLoader();



The other button, when clicked, calls another function, say resetAll, that then resets the "session" by clearing out all the current variables and canceling anything currently in progress. Within that function I want to call myLoader.close(myRequest); but myLoader is not accessible from within resetAll.

In this case, should I declare var myRequest:URLRequest=new URLRequest("*URL*"); and var myLoader:URLLoader = new URLLoader(); outside of the function even if I do not need them yet?

I think I am missing some common sense knowledge of AS3 here, but not sure what it is. It would be appreciated if someone could fill me in on best practice in this case.

You can declare URLLoader variable globally and use local declaration or URLRequest variable.

URLRequest is anyway you have to recreate for every new requests, declaring them locally would be more safer for GC to collect it after its use.

URLLoader makes no sence re creating everytime, you can just pass new URLReqest object into Load method everytime you want to load something from server.