2

I basically want to convert a string containing code like this -

var code = "function Solve(args) { // do stuff and return value};";

into an executable function which you can pass arguments. When I use it with eval(code + "Solve(args);"); It gives me no errors but the results are not as expected. I also tried:

var fu = eval(code);
var result = fu(args);

fu stays undefined. Am I doing something wrong or is there a better way to do this.

3
  • What do you mean by "the results are not as expected." What do you expect to happen? What does happen? Why is that incorrect? Commented Feb 12, 2014 at 13:34
  • The arguments are passed correctly but the result from the function is wrong. Commented Feb 12, 2014 at 13:35
  • 1
    Then maybe posting the actual body of the function rather than // do stuff and return value might be helpful? Commented Feb 12, 2014 at 13:36

4 Answers 4

3

Using eval is normally a very bad way of doing things.

eval is going to put the code into the Global namespace

var code = "function Solve(args) { return args * 2}";  
eval(code); 
var val = 1;
var result = Solve(val);

if you do not know the name, you would have to do something like this

var code = "function Solve2(args) { return args * 2}";
var val = 3;  
var result = eval("(" + code + ")(" + val + ");"); 

problem with the above method is it will use toString()

A better way to make a function from a string is using new Function

var sumCode = "return a + b";
var sum = new Function("a","b", sumCode);
sum(1,2); 
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you. I found my mistake. I think this approuch is the best because if you want to reuse the function with different args you can do it.
2

this works on jsfiddle:

var code = "function Solve(args) { alert(args)};"; 
eval(code + "Solve('test');");

what is the function and result you expect?

Comments

0

Just try with:

eval(code + "fu = Solve(args);");

console.log(fu);

Comments

0

All the other answers proposed using eval, so here is a mildly different approach.

Try this and tell me how you like it:

var code = "alert('I am an alert')";
var codeToFunction = new Function(code);
codeToFunction();

Comments

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.