简体   繁体   English

将字符串更改为 javascript 中的函数(不是 eval)

[英]changing string to a function in javascript (not eval)

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?我已经尝试了上述但它不起作用有没有其他方法可以在不使用 eval 的情况下执行该函数?

thnx谢谢

you want to use the Function constructor directly, as Anders said.正如 Anders 所说,您想直接使用Function构造Function 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 .在您的情况下,您有"function (){ alert('meee'); }"并且您想将其保存为 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. Functioneval的区别在于eval运行在私有范围内,而Function运行在全局范围内。

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 ).不要尝试在控制台中运行它,你会得到一个欺骗性的结果(控制台使用eval )。 Writing it in a <script> tag and loading it in the browser will give the true result.将它写在<script>标签中并在浏览器中加载它会给出真实的结果。

According to MDC .根据MDC Use:用:

var multiply = new Function("x", "y", "return x * y");
var theAnswer = multiply(7, 6);

不是我所知道的......可能有更好的方法来做你想做的事情,而不会让自己容易受到脚本注入攻击,这种攻击不涉及将javascript作为字符串传递。

example js code in string字符串中的示例js代码

 var theInstructions = "function sm(){ alert('meee'); } sm()"; var F=new Function (theInstructions); F.apply(null)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM