I have string containg anonymus function definition, but how i can call this. Lets say function is like so:
var fn_str = "function(){ alert('called'); }";
Tried eval, but got an error that function must have a name.
eval(fn_str).apply(this); // SyntaxError: function statement requires a name
You can use Immediately Invoked Function Expression:
var fn_str = "function(){ alert('called'); }";
eval('(' + fn_str +')();');
Immediately Invoked Function Expression
Another way is to use to a Function
object (If you have the function body string):
var func = new Function("alert('called')");
func.apply(this);
You can create functions from strings using the Function constructor:
var fn = new Function("arg1", "alert('called ' + arg1);");
fn.apply(this)
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With