1.语法(最后一个参数一定是函数体,其余参数都作为传给函数体的参数。)
let func = new Function ([arg1, arg2, ...argN], functionBody);
例如:
let sum = new Function('a', 'b', 'return a + b'); console.log(sum(1, 2)); // 结果是 3
2.特性(那就是函数体的数据格式是字符串,这可是个不得了的东西啊!)
3.使用场景
①非合法 JSON 对象字符串合法化
let str = `{ "id": 1023, name: 'James', 'date': '2022-07-07' }`;
其中的字符串不符合 JSON 格式(键值需要双引号),此时如果使用 JSON.parse() 进行解析是会报错的。
很多人会想到进行正则匹配再替换,或者使用 eval 这样糟粕的属性进行处理。
无需这么麻烦,new Function 出马,马到成功!
console.log(JSON.stringify(new Function('return ' + str)())); // 返回结果是:'{"id":1023,"name":"James","date":"2022-07-07"}'
注意点:new Function 主体参数中的变量的上下文是全局的,而不是私有的,没有所谓的闭包。(不存在词法作用域)
浙公网安备 33010602011771号