0

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);
puppeteer701
  • 1,225
  • 3
  • 17
  • 33

1 Answers1

2

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";')
Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
  • I need to save function in a mongodb, any suggestions? – puppeteer701 Dec 29 '15 at 14:46
  • `need`? Why? Perhaps you could explain what you are trying to do. – Xotic750 Dec 29 '15 at 14:50
  • Why would you need to save a function ? This will be very slow and will lead to bugs and of course security problems if you're taking user inputs to do so. You should rather model the problem and define a structure enabling the reproduction of the behavior. See also http://stackoverflow.com/questions/197769/when-is-javascripts-eval-not-evil – Denys Séguret Dec 29 '15 at 14:52
  • the function is a callback and it can be different on every entry. – puppeteer701 Dec 29 '15 at 15:09