Eval a string to a callable JS function

给你一囗甜甜゛ 提交于 2019-12-10 22:18:21

问题


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!


回答1:


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



回答2:


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


来源:https://stackoverflow.com/questions/17792271/eval-a-string-to-a-callable-js-function

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!