You may come in a situation, where you need to call a function of which you do not know the name. Lets say, you have a swicth, there turns functionality on or off. If the switch is on, you call functionA() and you call functionB() if it's set to off. To do that, you can use the array acces operator (square brackets) to access the function at a specific scope. Take a look at the following:
import flash.events.MouseEvent;
var funcName:String = "functionA";
function functionA():void
{
messages.text +="functionA() is called\n";
}
function functionB():void
{
messages.text +="functionB() is called\n";
}
switchBtn.addEventListener(MouseEvent.CLICK, onSwitch, false, 0, true);
function onSwitch(e:MouseEvent):void
{
if(switchBtn.selected)
{
funcName = "functionB";
} else
{
funcName = "functionA";
}
}
showBtn.addEventListener(MouseEvent.CLICK, onShow, false, 0, true);
function onShow(e:MouseEvent):void
{
this[funcName]();
}
In this example there is thre components on stage. A checkbox (switchBtn), a button (showBtn) and a textfield (messages). First, a variable of the type String is declared to hold the name of the function to be called. It is initialized with "functionA" so something is ready to called in case of a click on showBtn.
Then the two function is declared. Here, they just update messages with a line of text, so you can se the difference between the two states.
A listener is set up, listening for a click on the checkbox. When onSwitch() is triggered, it checks to see whether the checkbox is selected or not, and updates the string funcName accordingly.
Then a listener is registered for a click on showBtn. When it is triggered the dynamic call is executed. By pointing to this and using an array access operator, you are able to access all objects in the current scope. When passing a variable name, it will always be evaluated before used, so you will end up passing the string contained instead of the variable name itself. After that, a set of parentheses is set, so it will execute as a function call, and not a dynamic called variable name.
Take a look at the attached fla-file for a working sample