lisovaccaro
lisovaccaro

Reputation: 33996

Javascript change string to type function?

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

Answers (4)

Aesthete
Aesthete

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

David G
David G

Reputation: 96845

Try this:

var act = 'alert(5);';

act = new Function( act );

Upvotes: 2

slebetman
slebetman

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

Akhil Sekharan
Akhil Sekharan

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

Related Questions