Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

dynamically call a function

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?

like image 289
sandy Avatar asked Dec 10 '25 10:12

sandy


2 Answers

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();
like image 76
grapefrukt Avatar answered Dec 12 '25 15:12

grapefrukt


From taskinoor's answer to this question:

instance1[functionName]();

Check this for some details.

like image 25
Jason Towne Avatar answered Dec 12 '25 14:12

Jason Towne