JavaScript - Function() 构造函数
Function() 构造函数
JavaScript 的 Function() 构造函数可以在运行时动态创建函数对象。使用 Function() 构造函数创建的函数仅具有全局作用域。
Function() 构造函数可用于在运行时定义函数,但应谨慎使用 Function() 构造函数,因为它可能导致代码漏洞。
我们可以向 Function() 构造函数传递多个参数。除最后一个参数外,所有参数均为待创建新函数中参数的名称。最后一个参数是函数体。
语法
以下是在 JavaScript 中使用 Function() 构造函数创建函数对象的语法
const obj = new Function(arg1, arg2..., functionBody);
Function() 构造函数可以使用或不使用 new 关键字来创建新的函数对象。所有参数均为 JavaScript 字符串。
参数
arg1, arg2... − 这些是函数体中使用的参数(可选)名称。这些名称将被视为待创建的函数中的参数名称。
functionBody − 此参数包含构成函数定义的 JavaScript 语句。
示例
在下面的示例中,我们向 Function() 构造函数传递了 3 个参数。前两个参数是 func() 函数的参数,第三个参数是 func() 函数的函数体。
在输出中,func() 函数返回 5 和 7 的乘积。
<html>
<body>
<p id = "output"> </p>
<script>
const func = new Function("p", "q", "return p * q");
document.getElementById("output").innerHTML =
"The value returned from the function is: " + func(5, 7);
</script>
</body>
</html>
输出
The value returned from the function is: 35
示例
在下面的示例中,我们将一个参数传递给 Function() 构造函数。因此,它会将其视为函数体。除最后一个参数外,所有参数都是可选的。
在输出中,您可以观察到 func() 函数返回 10 加 20 的和。
<html>
<body>
<p id = "output"> </p>
<script>
const func = new Function("return 10 + 20");
document.getElementById("output").innerHTML =
"The value returned from the function is: " + func();
</script>
</body>
</html>
输出
The value returned from the function is: 30
函数声明或函数表达式作为参数
使用 Function 构造函数创建函数的效率低于使用函数声明或函数表达式创建函数并在代码中调用它。
我们可以在 Function() 构造函数的 functionBody 参数中编写多个语句。所有语句之间用分号分隔。我们可以使用 函数声明 或 函数表达式 创建函数,并将其作为语句传递给 fucntionBody 参数。
示例
在此示例中,我们使用函数表达式定义了一个 sum 函数,并将其作为参数(functionBody)的一部分传递给 Function() 构造函数。此处需要 return 语句。
<html>
<body>
<p id = "output"> </p>
<script>
const add = new Function(
"const sum = function (a, b) {return a+ b}; return sum",
)();
document.getElementById("output").innerHTML = add(5,10) // 15
</script>
</body>
</html>
示例
在此示例中,我们定义了一个带有函数声明的匿名函数,并将其作为参数(functionBody)的一部分传递给 Function() 构造函数。此处末尾的 return 语句并非必需。
<html>
<body>
<p id = "output"> </p>
<script>
const sayHello = new Function(
"return function (name) { return `Hello, ${name}` }",
)();
document.getElementById("output").innerHTML =
sayHello("world"); // Hello, world
</script>
</body>
</html>
请注意,在上面的两个例子中,新函数都是自调用的。

