Reputation: 117
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.
Upvotes: 2
Views: 852
Reputation: 5107
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();
Upvotes: 0
Reputation: 207511
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);
Upvotes: 3
Reputation: 4218
this works on jsfiddle:
var code = "function Solve(args) { alert(args)};";
eval(code + "Solve('test');");
what is the function and result you expect?
Upvotes: 2