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

发布于 2024-07-30 11:50:57 字数 394 浏览 5 评论 0原文

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

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

现在,我执行 eval() 来实际在变量中获取该函数。

var func = eval(funcStr);

如果我没记错的话,在 Chrome 和 Opera 中,只需调用

func();

即可调用该函数并显示警报。

但是,在其他浏览器中情况并非如此。 什么都没发生。

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

I have a function and its contents as a string.

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

Now, I do an eval() to actually get that function in a variable.

var func = eval(funcStr);

If I remember correctly, in Chrome and Opera, simply calling

func();

invoked that function and the alert was displayed.

But, in other browsers it wasn't the case. nothing happened.

I don't want an arguement about which is the correct method, but how can I do this? I want to be able to call variable(); to execute the function stored in that variable.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(11

你如我软肋 2024-08-06 11:50:58

我意识到这是旧的,但它是我在谷歌搜索中评估匿名 JavaScript 函数字符串时出现的唯一有效结果。

我终于从 jquery google 组的帖子中弄清楚了如何做到这一点。

eval("false||"+data)

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

到目前为止,我只在 IE8 和 FF8 (我个人计算机上的浏览器)中尝试过这个,但我相信 jquery 在内部使用它,所以它应该可以工作几乎无处不在。

I realize this is old, but it was the only valid result coming up in my google searches for evaluating anonymous javascript function strings.

I finally figured out how to do it from a post on the jquery google group.

eval("false||"+data)

where data is your function string like "function() { return 123; }"

So far, I have only tried this in IE8 and FF8 (the browsers on my personal computer), but I believe jquery uses this internally so it should work just about everywhere.

ㄖ落Θ余辉 2024-08-06 11:50:58

尝试

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

eval(funcStr);

func();

Try

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

eval(funcStr);

func();
不念旧人 2024-08-06 11:50:58

像这样使用 eval :

var func = eval('(' + funcStr + ')');

Use the eval like this :

var func = eval('(' + funcStr + ')');
穿越时光隧道 2024-08-06 11:50:58

我们通过准备通用函数解析器将字符串转换为真正的 JavaScript 函数来解决这个问题:

if (typeof String.prototype.parseFunction != 'function') {
    String.prototype.parseFunction = function () {
        var funcReg = /function *\(([^()]*)\)[ \n\t]*{(.*)}/gmi;
        var match = funcReg.exec(this.replace(/\n/g, ' '));

        if(match) {
            return new Function(match[1].split(','), match[2]);
        }

        return null;
    };
}

使用示例:

var func = 'function (a, b) { return a + b; }'.parseFunction();
alert(func(3,4));

func = 'function (a, b) { alert("Hello from function initiated from string!"); }'.parseFunction();
func();

此处 是 jsfiddle

We solved this problem by preparing universal function parser that convert string to real JavaScript function:

if (typeof String.prototype.parseFunction != 'function') {
    String.prototype.parseFunction = function () {
        var funcReg = /function *\(([^()]*)\)[ \n\t]*{(.*)}/gmi;
        var match = funcReg.exec(this.replace(/\n/g, ' '));

        if(match) {
            return new Function(match[1].split(','), match[2]);
        }

        return null;
    };
}

examples of usage:

var func = 'function (a, b) { return a + b; }'.parseFunction();
alert(func(3,4));

func = 'function (a, b) { alert("Hello from function initiated from string!"); }'.parseFunction();
func();

here is jsfiddle

拿命拼未来 2024-08-06 11:50:58

这也可以。

var func = eval("_="+funcStr);

This is also ok.

var func = eval("_="+funcStr);
破晓 2024-08-06 11:50:58

没有 eval() 的 EVAL...

function evalEx(code){
  var result,D=document,S=D.createElement('script'),
  H=D.head||D.getElementsByTagName['head'][0],
  param=Array.prototype.slice.call(arguments);
  code='function evalWE(){'+code+'}';
  S.innerText===''?S.innerText=code:S.textContent=code;
  H.appendChild(S);
  result=evalWE.apply(this,param);
  H.removeChild(S);
  return result
}

用法示例:

ABC=evalEx('return "ABC"');
nine=evalEx('return arguments[1]+arguments[2]',4,5);

EVAL without eval()...

function evalEx(code){
  var result,D=document,S=D.createElement('script'),
  H=D.head||D.getElementsByTagName['head'][0],
  param=Array.prototype.slice.call(arguments);
  code='function evalWE(){'+code+'}';
  S.innerText===''?S.innerText=code:S.textContent=code;
  H.appendChild(S);
  result=evalWE.apply(this,param);
  H.removeChild(S);
  return result
}

Usage Example:

ABC=evalEx('return "ABC"');
nine=evalEx('return arguments[1]+arguments[2]',4,5);
小姐丶请自重 2024-08-06 11:50:58

进行 eval() 处理,并在立即调用函数时传入参数(然后将结果转储到控制台):

一个简单的示例,将函数定义为字符串,对其
console.log('eval: %s', eval("(function(foo) { return foo.bar; })")({"bar": "12345"}));

这会产生如下所示的输出。

<代码>
评估:12345

A simple example of defining a function as a string, eval()ing it, and passing in a parameter while immediately invoking the function (and then dumping the result to the console):


console.log('eval: %s', eval("(function(foo) { return foo.bar; })")({"bar": "12345"}));

This produces output like the following.


eval: 12345

虫児飞 2024-08-06 11:50:58

同样有效的是

var myFunc = function(myParam){
   // function body here
}

What also works is

var myFunc = function(myParam){
   // function body here
}
忆悲凉 2024-08-06 11:50:58

function-serialization-tools 提供了一个函数 s2f(),它采用字符串表示形式一个函数并将其作为函数返回。

function-serialization-tools provides a function, s2f(), that takes a string representation of a function and returns it as a function.

铃予 2024-08-06 11:50:57

这个怎么样?

var func = new Function('alert("hello");');

向函数添加参数:

var func = new Function('what', 'alert("hello " + what);');
func('world'); // hello world

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

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

function executeSomething(something) {
    something();
}
executeSomething(otherFunc); // Alerts 'hello'

How about this?

var func = new Function('alert("hello");');

To add arguments to the function:

var func = new Function('what', 'alert("hello " + what);');
func('world'); // hello world

Do note that functions are objects and can be assigned to any variable as they are:

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

function executeSomething(something) {
    something();
}
executeSomething(otherFunc); // Alerts 'hello'
遗弃M 2024-08-06 11:50:57

IE 无法eval 函数(大概是出于安全原因)。

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

var func = eval('[' + funcStr + ']')[0];

IE cannot eval functions (Presumably for security reasons).

The best workaround is to put the function in an array, like this:

var func = eval('[' + funcStr + ']')[0];
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文