I need to eval a function kept as string and then use it in JS code, here's the scenario:
Step 1
<textarea id="function_text">function test(e){ alert(e.id); }</textarea>
Step 2
var thatFunction = eval($("#function_text").val()); // returns undefined
Step 3
thatFunction.call({id: 100});
Is there a way to do that?
P.S. I'm aware of all security considerations, I just need 100 to be alerted at step 3!
I'm going to give you a warning, don't do it, but here is how:
var thatFunction = Function('return ' + $("#function_text").val())();
thatFunction.call({id: 100});
The code in the string will be evaluated as function declaration and not produce a return value, and that's why eval
returns undefined
.
You could concatenate the function declaration with your variable assignment:
eval('var thatFunction = ' + $("#function_text").val());
or simply call the function by the name it has (it you know it):
test.call({id: 100});
You might not want to use the variable name in the string. That's not a problem, all you have to do is force eval
to consider the function definition as function expression and have it return the function. For example, you can do this by using the grouping operator:
var thatFunction = eval('(' + $("#function_text").val() + ')');
A more obscure way would be the comma operator:
var thatFunction = eval('0,' + $("#function_text").val());