PDA

View Full Version : about variable scope


windec
06-09-2009, 01:57 PM
Sorry for this bad example. This is just for my understanding purpose. If the result:number works as something that is stored somewhere outside the box and can be accessed from everywhere in the application that can be nice. How to make the result:number as a global variable?.




private function multiplyby():void
{
var result:Number;
var initialnum:Number;
var multiplier:Number;
multiplier=numslide.value.valueOf();
initialnum=Number(numinput.text);
result=multiplier*initialnum;
numinput.text=result.toString();
dividedby3(result);
}
private function dividedby3(result):void
{
var result2:Number;
result2=result/3;
numinput2.text=result2.toString();
}
]]>
</mx:Script>

<mx:HSlider id="numslide" minimum="2" maximum="12" snapInterval="1"/>
<mx:Label text="enter num 1" x="65" y="40" />
<mx:TextInput id="numinput" x="65" y="120"/>
<mx:Button label="multiply by slider value" id="numbutton" click="multiplyby()"/>
<mx:Label text=" num 1 divided by 3" x="65" y="40" />
<mx:TextInput id="numinput2" x="65" y="120"/>

mattb
06-13-2009, 04:33 AM
First a brief warning: global variables should really be avoided wherever possible. You open yourself up to a whole load of potential issues. If your app grows in size you can quickly struggle to determine where the global variables are being set which can be a nightmare in debugging, plus it can be inefficient.

OK, if you really want/need to do this, you can access your application MXML class from any point in your code using Application.application. So if you have a variable declared as public in your app MXML file:


<mx:Code>
<![CDATA[
public var result:Number = 99;
]]>
</mx:Code>


You can get this result at any time like this:


trace("Result: " + Application.application.result);