执行使用JavaScript eval()创建的匿名函数

17 javascript eval

我有一个函数及其内容作为字符串.

var funcStr = "function() { alert('hello'); }";
Run Code Online (Sandbox Code Playgroud)

现在,我做一个eval()来实际在变量中获取该函数.

var func = eval(funcStr);
Run Code Online (Sandbox Code Playgroud)

如果我没记错的话,在Chrome和Opera中,只需拨打电话即可

func();
Run Code Online (Sandbox Code Playgroud)

调用该函数并显示警报.

但是,在其他浏览器中并非如此.没啥事儿.

我不想争论哪种方法是正确的,但我怎么能这样做呢?我希望能够调用variable(); 执行存储在该变量中的函数.

Bli*_*ixt 33

这个怎么样?

var func = new Function('alert("hello");');
Run Code Online (Sandbox Code Playgroud)

要为函数添加参数:

var func = new Function('what', 'alert("hello " + what);');
func('world'); // hello world
Run Code Online (Sandbox Code Playgroud)

请注意,函数是对象,可以按原样分配给任何变量:

var func = function () { alert('hello'); };
var otherFunc = func;
func = 'funky!';

function executeSomething(something) {
    something();
}
executeSomething(otherFunc); // Alerts 'hello'
Run Code Online (Sandbox Code Playgroud)


SLa*_*aks 14

IE无法eval运行(大概是出于安全考虑).

最好的解决方法是将函数放在一个数组中,如下所示:

var func = eval('[' + funcStr + ']')[0];
Run Code Online (Sandbox Code Playgroud)

  • @Juan:错了; 这不可以.尝试`javascript:alert(eval('(function(){return 3;})'));` (3认同)

use*_*862 8

我意识到这是旧的,但这是我谷歌搜索中评估匿名javascript函数字符串的唯一有效结果.

我终于想出了如何从jquery google组的帖子中做到这一点.

eval("false||"+data)
Run Code Online (Sandbox Code Playgroud)

其中data是你的函数字符串,如"function(){return 123;}"

到目前为止,我只在IE8和FF8(我的个人计算机上的浏览器)中尝试过这个,但我相信jquery在内部使用它,因此它应该适用于任何地方.


Dav*_*son 6

尝试

var funcStr = "var func = function() { alert('hello'); }";

eval(funcStr);

func();
Run Code Online (Sandbox Code Playgroud)