Reputation: 1285
I would like to convert a function that is a string now to Function.
This returns an error, any suggestions?
var a = 'function () { return "a"; }'.trim();
console.log(a);
var b = eval(a);
Upvotes: 0
Views: 41
Reputation: 382122
A "solution" would be to add parenthesis around the string, in order to evaluate an expression :
var a = 'function () { return "a"; }'.trim();
console.log(a);
var b = eval('('+a+')');
But it's clear you're after a bad design. There's no problem that should be solved that way.
Note that it's marginally more secure to use the Function constructor (which has no access to local variables) than to use eval
:
var fun = new Function('return "a";')
Upvotes: 2