handler.construct()

handler.construct() 方法是 [[Construct]] 对象内部方法 的陷阱,被 new 运算符等操作使用。为了使 new 操作在生成的 Proxy 对象上有效,用于初始化代理的目标本身必须是有效的构造函数。

¥The handler.construct() method is a trap for the [[Construct]] object internal method, which is used by operations such as the new operator. In order for the new operation to be valid on the resulting Proxy object, the target used to initialize the proxy must itself be a valid constructor.

Try it

语法

¥Syntax

js
new Proxy(target, {
  construct(target, argumentsList, newTarget) {
  }
});

参数

¥Parameters

以下参数传递给 construct() 方法。this 绑定到处理程序。

¥The following parameters are passed to the construct() method. this is bound to the handler.

target

目标对象。

argumentsList

构造函数的参数列表。

newTarget

最初调用的构造函数。

返回值

¥Return value

construct 方法必须返回一个对象。

¥The construct method must return an object.

描述

¥Description

拦截

¥Interceptions

该陷阱可以拦截以下操作:

¥This trap can intercept these operations:

或调用 [[Construct]] 内部方法 的任何其他操作。

¥Or any other operation that invokes the [[Construct]] internal method.

不变量

¥Invariants

如果违反以下不变量,则陷阱在调用时会抛出 TypeError

¥If the following invariants are violated, the trap throws a TypeError when invoked.

  • 结果必须是 Object

示例

¥Examples

捕获新运算符

¥Trapping the new operator

以下代码捕获 new 运算符。

¥The following code traps the new operator.

js
const p = new Proxy(function () {}, {
  construct(target, argumentsList, newTarget) {
    console.log(`called: ${argumentsList}`);
    return { value: argumentsList[0] * 10 };
  },
});

console.log(new p(1).value); // "called: 1"
// 10

以下代码违反了不变量。

¥The following code violates the invariant.

js
const p = new Proxy(function () {}, {
  construct(target, argumentsList, newTarget) {
    return 1;
  },
});

new p(); // TypeError is thrown

以下代码未正确初始化代理。代理初始化中的 target 本身必须是 new 运算符的有效构造函数。

¥The following code improperly initializes the proxy. The target in Proxy initialization must itself be a valid constructor for the new operator.

js
const p = new Proxy(
  {},
  {
    construct(target, argumentsList, newTarget) {
      return {};
    },
  },
);

new p(); // TypeError is thrown, "p" is not a constructor

规范

Specification
ECMAScript Language Specification
# sec-proxy-object-internal-methods-and-internal-slots-construct-argumentslist-newtarget

¥Specifications

浏览器兼容性

BCD tables only load in the browser

¥Browser compatibility

也可以看看