Function() 构造函数

Function() 构造函数创建 Function 对象。直接调用构造函数可以动态创建函数,但会遇到安全性和与 eval() 类似(但远不那么重要)的性能问题。但是,与 eval(可以访问本地作用域)不同,Function 构造函数创建仅在全局作用域中执行的函数。

¥The Function() constructor creates Function objects. Calling the constructor directly can create functions dynamically, but suffers from security and similar (but far less significant) performance issues as eval(). However, unlike eval (which may have access to the local scope), the Function constructor creates functions which execute in the global scope only.

Try it

语法

¥Syntax

js
new Function(functionBody)
new Function(arg1, functionBody)
new Function(arg1, arg2, functionBody)
new Function(arg1, arg2, /* …, */ argN, functionBody)

Function(functionBody)
Function(arg1, functionBody)
Function(arg1, arg2, functionBody)
Function(arg1, arg2, /* …, */ argN, functionBody)

注意:可以使用或不使用 new 来调用 Function()。两者都会创建一个新的 Function 实例。

¥Note: Function() can be called with or without new. Both create a new Function instance.

参数

¥Parameters

arg1, …, argN Optional

函数用作形式参数名称的名称。每个都必须是与有效 JavaScript 参数(任何纯 identifier剩余参数destructured 参数,可选地带有 default)相对应的字符串,或者是用逗号分隔的此类字符串的列表。

由于参数的解析方式与函数表达式相同,因此接受空格和注释。例如:"x", "theValue = 42", "[a, b] /* numbers */" — 或 "x, theValue = 42, [a, b] /* numbers */"。("x, theValue = 42", "[a, b]" 也是正确的,尽管读起来很混乱。)

functionBody

包含构成函数定义的 JavaScript 语句的字符串。

描述

¥Description

使用 Function 构造函数创建的 Function 对象在创建函数时进行解析。这比使用 函数表达式函数声明 创建函数并在代码中调用它的效率要低,因为此类函数是与代码的其余部分一起解析的。

¥Function objects created with the Function constructor are parsed when the function is created. This is less efficient than creating a function with a function expression or function declaration and calling it within your code, because such functions are parsed with the rest of the code.

传递给函数的所有参数(除了最后一个参数)都被视为要创建的函数中参数的标识符名称,按照传递的顺序排列。该函数将动态编译为函数表达式,源代码按以下方式组装:

¥All arguments passed to the function, except the last, are treated as the names of the identifiers of the parameters in the function to be created, in the order in which they are passed. The function will be dynamically compiled as a function expression, with the source assembled in the following fashion:

js
`function anonymous(${args.join(",")}
) {
${functionBody}
}`;

这可以通过调用函数的 toString() 方法来观察。

¥This is observable by calling the function's toString() method.

然而,与普通的 函数表达式 不同,名称 anonymous 不会添加到 functionBody 的作用域中,因为 functionBody 只能访问全局作用域。如果 functionBody 不在 严格模式 中(主体本身需要有 "use strict" 指令,因为它不继承上下文的严格性),你可以使用 arguments.callee 来引用函数本身。或者,你可以将递归部分定义为内部函数:

¥However, unlike normal function expressions, the name anonymous is not added to the functionBody's scope, since functionBody only has access the global scope. If functionBody is not in strict mode (the body itself needs to have the "use strict" directive since it doesn't inherit the strictness from the context), you may use arguments.callee to refer to the function itself. Alternatively, you can define the recursive part as an inner function:

js
const recursiveFn = new Function(
  "count",
  `
(function recursiveFn(count) {
  if (count < 0) {
    return;
  }
  console.log(count);
  recursiveFn(count - 1);
})(count);
`,
);

请注意,组装源代码的两个动态部分 - 参数列表 args.join(",")functionBody - 将首先被单独解析,以确保它们在语法上都是有效的。这可以防止类似注入的尝试。

¥Note that the two dynamic parts of the assembled source — the parameters list args.join(",") and functionBody — will first be parsed separately to ensure they are each syntactically valid. This prevents injection-like attempts.

js
new Function("/*", "*/) {");
// SyntaxError: Unexpected end of arg string
// Doesn't become "function anonymous(/*) {*/) {}"

示例

¥Examples

使用 Function 构造函数指定参数

¥Specifying arguments with the Function constructor

以下代码创建一个带有两个参数的 Function 对象。

¥The following code creates a Function object that takes two arguments.

js
// Example can be run directly in your JavaScript console

// Create a function that takes two arguments, and returns the sum of those arguments
const adder = new Function("a", "b", "return a + b");

// Call the function
adder(2, 6);
// 8

参数 ab 是函数体 return a + b 中使用的正式参数名称。

¥The arguments a and b are formal argument names that are used in the function body, return a + b.

从函数声明或函数表达式创建函数对象

¥Creating a function object from a function declaration or function expression

js
// The function constructor can take in multiple statements separated by a semicolon. Function expressions require a return statement with the function's name

// Observe that new Function is called. This is so we can call the function we created directly afterwards
const sumOfArray = new Function(
  "const sumArray = (arr) => arr.reduce((previousValue, currentValue) => previousValue + currentValue); return sumArray",
)();

// call the function
sumOfArray([1, 2, 3, 4]);
// 10

// If you don't call new Function at the point of creation, you can use the Function.call() method to call it
const findLargestNumber = new Function(
  "function findLargestNumber (arr) { return Math.max(...arr) }; return findLargestNumber",
);

// call the function
findLargestNumber.call({}).call({}, [2, 4, 1, 8, 5]);
// 8

// Function declarations do not require a return statement
const sayHello = new Function(
  "return function (name) { return `Hello, ${name}` }",
)();

// call the function
sayHello("world");
// Hello, world

规范

Specification
ECMAScript Language Specification
# sec-function-constructor

¥Specifications

浏览器兼容性

BCD tables only load in the browser

¥Browser compatibility

也可以看看