将字符串评估为可调用的JS函数 [英] Eval a string to a callable JS function
本文介绍了将字符串评估为可调用的JS函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要评估一个保存为字符串的函数,然后在JS代码中使用它,这是这种情况:
I need to eval a function kept as string and then use it in JS code, here's the scenario:
第1步
<textarea id="function_text">function test(e){ alert(e.id); }</textarea>
第2步
var thatFunction = eval($("#function_text").val()); // returns undefined
第3步
thatFunction.call({id: 100});
有办法吗?
P.S.我知道所有安全注意事项,在第3步中只需要100个警报即可!
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});
这篇关于将字符串评估为可调用的JS函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文