将字符串更改为javascript中的函数(而不是eval) [英] changing string to a function in javascript (not eval)
问题描述
var foo =function(){alert('meee');};
foo();
我已经尝试了上述方法,但它不起作用,有没有其他方法可以在不使用eval?
要使用<$正如Anders所说,直接使用c $ c> Function 构造函数。所有参数都是字符串。最后一个参数是函数的主体,任何主要参数都是函数所用参数的名称。
借用Anders的例子,
var multiply = new函数(x,y,return x * y);
将会像写作一样
var multiply = function(x,y){
return x * y
}
在你的情况下,你有function(){alert('meee');}
,你想把它保存为函数var foo
。
var fn =function(){ alert('meee');};
var foo = new Function(return(+ fn +))();
foo();
// alertsmeee
函数
和 eval
是 eval
运行在私人范围内,而功能
在全局范围内运行。
var x =haha,y =hehe;
函数test(){
var x = 15,y = 34;
eval(alert('eval:'+ x +','+ y));
new Function(alert('Func:'+ x +','+ y))();
}
test();
// eval:15,34
// Func:haha,hehe
不要试图在控制台中运行它,你会得到一个欺骗结果(控制台使用 eval
)。将它写入< script>
标记并将其加载到浏览器中将会给出真正的结果。
var foo = "function (){ alert('meee'); }";
foo();
I have tried the above but it does not work is there any other way to execute that function without using eval?
thnx
you want to use the Function
constructor directly, as Anders said. All arguments are strings. The last argument is the body of the function, any leading arguments are the names of the arguments the function takes.
To borrow from Anders' example,
var multiply = new Function("x", "y", "return x * y");
would be like writing
var multiply = function (x,y) {
return x * y
}
In your case, you have "function (){ alert('meee'); }"
and you want to save it as a function to var foo
.
var fn = "function (){ alert('meee'); }";
var foo = new Function("return ("+fn+")")();
foo();
// alerts "meee"
The difference between Function
and eval
is eval
runs in the private scope, while Function
runs in the global scope.
var x="haha", y="hehe";
function test () {
var x=15, y=34;
eval("alert('eval: ' + x + ', ' + y)");
new Function("alert('Func: ' + x + ', ' + y)")();
}
test();
// eval: 15, 34
// Func: haha, hehe
Don't try to run it in the console, you'll get a deceiving result (consoles use eval
). Writing it in a <script>
tag and loading it in the browser will give the true result.
这篇关于将字符串更改为javascript中的函数(而不是eval)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!