有没有一种方法来创建一个JavaScript的字符串函数? [英] Is there a way to create a function from a string with javascript?

查看:86
本文介绍了有没有一种方法来创建一个JavaScript的字符串函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如;

  var s =function test(){
alert(1);
};

var fnc = aMethod(s);

如果这是字符串,我想要一个叫做fnc的函数。

eval(alert(1)) fnc(); > pops alert screen。

;)不解决我的问题。

解决方案

通过使用 Function

  var fn = Function(alert( '你好')); 
fn();

当前范围中的变量(如果不是全局变量)不适用于

传递参数也是可能的:

  var addition = Function(a,b,return a + b;); 
alert(addition(5,3)); //显示'8'


For example;

var s = "function test(){
  alert(1);
}";

var fnc = aMethod(s);

If this is the string, I want a function that's called fnc. And fnc(); pops alert screen.

eval("alert(1);") doesnt solve my problem.

解决方案

A better way to create a function from a string is by using Function:

var fn = Function("alert('hello there')");
fn();

This has as advantage / disadvantage that variables in the current scope (if not global) do not apply to the newly constructed function.

Passing arguments is possible too:

var addition = Function("a", "b", "return a + b;");
alert(addition(5, 3)); // shows '8'

这篇关于有没有一种方法来创建一个JavaScript的字符串函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆