Reputation: 293
How can we dynamically call a function. I have tried below code:
public function checkFunc() : void
{
Alert.show("inside function");
}
public var myfunc:String = "checkFunc";
public var newFunc:Function=Function(myfunc);
newFunc();
But it gives error:
Call to a possibly undefined method newFunc.
In place of newFunc()
, I tried calling it as this[newFunc]()
, but that throws error:
The this keyword can not be used in static methods. It can only be used in instance methods, function closures, and global code
Any help in calling the function dynamically?
Upvotes: 2
Views: 4162
Reputation: 27045
Functions work the same way properties to, you can assign them the same way you assign variables, meaning that all the funky square bracket tricks work for them too.
public function checkFunc() : void
{
Alert.show("inside function");
}
public var myfunc:String = "checkFunc";
public var newFunc:Function = this[myfunc];
newFunc();
Upvotes: 5
Reputation: 6403
Code not tested but should work
package {
public class SomeClass{
public function SomeClass( ):void{
}
public function someFunc( val:String ):void{
trace(val);
}
public function someOtherFunc( ):void{
this['someFunc']('this string is passed from inside the class');
}
}
}
// usage
var someClass:SomeClass = new SomeClass( );
someClass['someFunc']('this string is passed as a parameter');
someClass.someOtherFunc();
// mxml example
// Again untested code but, you should be able to cut and paste this example.
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" creationComplete="someOtherFunc( )" >
<mx:Script>
<;
}
]]>
</mx:Script>
<mx:Label id="theLabel" />
</mx:Application>
Upvotes: 2
Reputation: 7426
Functions in flash are Objects, and as such function just as any object does. The AS3 api shows that a function has a call() method. you are very close in your code:
// Get your functions
var func : Function = someFunction;
// call() has some parameters to achieve varying types of function calling and params
// I typically have found myself using call( null, args );
func.call( null ); // Calls a function
func.call( null, param1, param2 ); // Calls a function with parameters
Upvotes: 1
Reputation: 8050
From taskinoor's answer to this question:
instance1[functionName]();Check this for some details.
Upvotes: 3