new Function 是 JavaScript 中用于动态创建函数的构造函数,其核心特点是将函数参数和函数体作为字符串传入,最终返回一个可执行的函数对象。以下是详细用法及注意事项:
一、基本用法
const func = new Function([arg1, arg2, ...,] functionBody);
//arg1, arg2, ...:函数参数(字符串形式)。
//functionBody:函数体(字符串形式,需包含合法的 JavaScript 代码)。
// 创建一个加法函数
const add = new Function('a', 'b', 'return a + b');
console.log(add(2, 3)); // 输出 5
// 无参数函数
const sayHello = new Function("console.log('Hello')");
sayHello(); // 输出 "Hello"
//多行函数体
const multiply = new Function(
'a', 'b',
'console.log("Calculating..."); return a * b;'
);
console.log(multiply(4, 5)); // 输出 20