[Js茶话会]-new Function

2,407 阅读1分钟

new Function

它是创建函数的特殊写法,在非常特殊的情况下使用,例如当我们从服务器接收代码时,或者使用模板动态编译函数。对此的需求通常出现在开发的进阶阶段

创建函数的方法

  • 函数声明
function testA(){

}
  • 箭头函数
const testB = ()=> {

}
  • new Function

const testC = new Function('console.log(`aaa`)')
testC()

语法

let func = new Function ([arg1[, arg2[, ...argN]],] functionBody)
  • 例子
let sum = new Function('a''b''return a + b');
alert( sum(1, 2) ); // 3

与常规创建函数不同的地方

上一节我们说到词法作用域,在函数定义的时候就确认了变量的查找,但是new Function()创建函数时,其[[Environment]]不是引用当前的词法环境,而是引用全局环境。这明确地传递参数在架构上是一种更好的方法,并且不会在使用minifiers时不会产生问题。

  • demo 只有把value定义在全局才可以获取到,所以Function中的表达式使用的变量要么是传入的参数要么是全局的值
function getFunc() {
  let value = "test";

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

  return func;
}

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

应用

  • 字符串模板
const temp = new Function('data''return ' + 'Hello,`${data.name}`')

temp({name: '你好'})

// Hello,你好