Reputation: 33996
I have a list of functions stored as strings such as this one:
var act= "function () { alert() }";
I need to change the type of act from 'string' to 'function' so I can .call() it. I should end up with this:
act = function () { alert() };
How can this be done?
Upvotes: 1
Views: 1879
Reputation: 18848
You can use eval
, although it is considered to be particularly unsafe if the string source is unknown. You can't really assign what you have there to any variable. eval
argument has to be an expression or a statement. You can do something like this.
eval("var act = function () { alert('hey') }");
act();
Upvotes: 1
Reputation: 114004
This is one of the few cases where using eval is not only valid but correct:
var act = eval(function_string);
However, I should note that having a bunch of functions in strings is a sign of bad design. Still, if you must then eval is the way to do it.
Upvotes: 3
Reputation: 12693
I guess you have to do it with eval. But many people consider it as evil (Be sure that you get the string from a safe source.)
var act= "function () { alert() }";
eval ('act = '+ act)
Upvotes: 1