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);

1
  • 3
    Please tell us about the real problem you're trying to solve. Commented Dec 29, 2015 at 14:42

1 Answer 1

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";')
Sign up to request clarification or add additional context in comments.

4 Comments

I need to save function in a mongodb, any suggestions?
need? Why? Perhaps you could explain what you are trying to do.
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 stackoverflow.com/questions/197769/…
the function is a callback and it can be different on every entry.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.