函数

Function 对象为 functions 提供方法。在 JavaScript 中,每个函数实际上都是一个 Function 对象。

¥The Function object provides methods for functions. In JavaScript, every function is actually a Function object.

构造函数

¥Constructor

Function()

创建一个新的 Function 对象。直接调用构造函数可以动态创建函数,但会遇到与 eval() 类似(但不太重要)的安全性和性能问题。但是,与 eval() 不同,Function 构造函数创建仅在全局范围内执行的函数。

实例属性

¥Instance properties

这些属性在 Function.prototype 上定义并由所有 Function 实例共享。

¥These properties are defined on Function.prototype and shared by all Function instances.

Function.prototype.arguments Deprecated Non-standard

表示传递给该函数的参数。对于 strict、箭头、异步和生成器函数,访问 arguments 属性会抛出 TypeError。请改用函数闭包内的 arguments 对象。

Function.prototype.caller Deprecated Non-standard

代表调用该函数的函数。对于 strict、箭头、异步和生成器函数,访问 caller 属性会抛出 TypeError

Function.prototype.constructor

创建实例对象的构造函数。对于 Function 实例,初始值为 Function 构造函数。

这些属性是每个 Function 实例自己的属性。

¥These properties are own properties of each Function instance.

displayName Non-standard Optional

函数的显示名称。

length

指定函数期望的参数数量。

name

函数的名称。

prototype

当函数与 new 运算符一起用作构造函数时使用。它将成为新对象的原型。

实例方法

¥Instance methods

Function.prototype.apply()

使用给定的 this 值和以数组(或 类似数组的对象)形式提供的可选参数调用函数。

Function.prototype.bind()

创建一个新函数,在调用时将其 this 关键字设置为提供的值,可以选择在调用新函数时在任何提供的参数之前添加给定的参数序列。

Function.prototype.call()

使用给定的 this 值和可选参数调用函数。

Function.prototype.toString()

返回表示函数源代码的字符串。覆盖 Object.prototype.toString 方法。

Function.prototype[@@hasInstance]()

指定用于确定构造函数是否将对象识别为构造函数的实例之一的默认过程。由 instanceof 话务员调用。

示例

¥Examples

函数构造函数和函数声明之间的区别

¥Difference between Function constructor and function declaration

使用 Function 构造函数创建的函数不会为其创建上下文创建闭包;它们始终是在全局范围内创建的。运行它们时,它们只能访问自己的局部变量和全局变量,而不能访问创建 Function 构造函数的作用域中的变量。这与将 eval() 与函数表达式的代码一起使用不同。

¥Functions created with the Function constructor do not create closures to their creation contexts; they always are created in the global scope. When running them, they will only be able to access their own local variables and global ones, not the ones from the scope in which the Function constructor was created. This is different from using eval() with code for a function expression.

js
// Create a global property with `var`
var x = 10;

function createFunction1() {
  const x = 20;
  return new Function("return x;"); // this `x` refers to global `x`
}

function createFunction2() {
  const x = 20;
  function f() {
    return x; // this `x` refers to the local `x` above
  }
  return f;
}

const f1 = createFunction1();
console.log(f1()); // 10
const f2 = createFunction2();
console.log(f2()); // 20

虽然此代码可以在 Web 浏览器中运行,但 f1() 将在 Node.js 中生成 ReferenceError,因为找不到 x。这是因为 Node 中的顶层作用域不是全局作用域,并且 x 将是模块的本地作用域。

¥While this code works in web browsers, f1() will produce a ReferenceError in Node.js, as x will not be found. This is because the top-level scope in Node is not the global scope, and x will be local to the module.

规范

Specification
ECMAScript Language Specification
# sec-function-objects

¥Specifications

浏览器兼容性

BCD tables only load in the browser

¥Browser compatibility

也可以看看