Skip to content

new Function

new Function 允许我们将任意字符串变为函数。

let func = new Function ([arg1, arg2, ...argN], functionBody);
js
let sum = new Function("a", "b", "return a + b");

new Function 无法闭包

new Function 的 [[Environment]] 并不指向当前的词法环境(函数创建时的词法环境),而是指向全局环境。

js
function getFunc() {
  let value = "test";

  let func = new Function("alert(value)");

  return func;
}

getFunc()(); // error: value is not defined

压缩程序(minifier)可能会把 某个 值 压缩为 a,这种压缩对于 new Function 十分不好。