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

Val*_*Val 9 javascript string function

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

I have tried the above but it does not work is there any other way to execute that function without using eval?

thnx

Dag*_*bit 12

你想Function直接使用构造函数,正如Anders所说.所有参数都是字符串.最后一个参数是函数体,任何前导参数都是函数所采用的参数的名称.

借用安德斯的例子,

var multiply = new Function("x", "y", "return x * y");
Run Code Online (Sandbox Code Playgroud)

就像写作一样

var multiply = function (x,y) {
  return x * y
}
Run Code Online (Sandbox Code Playgroud)

在你的情况下,你有,"function (){ alert('meee'); }"并且你想将它作为函数保存到var foo.

var fn = "function (){ alert('meee'); }";
var foo = new Function("return ("+fn+")")();
foo();
// alerts "meee"
Run Code Online (Sandbox Code Playgroud)

之间的区别Function,并evaleval在私人范围内运行,而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
Run Code Online (Sandbox Code Playgroud)

不要试图在控制台中运行它,你会得到一个欺骗性的结果(控制台使用eval).将其写入<script>标签并将其加载到浏览器中将得到真实的结果.