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
语法
参数
¥Parameters
以下参数传递给 construct()
方法。this
绑定到处理程序。
¥The following parameters are passed to the construct()
method. this
is bound to the handler.
target
-
目标对象。
argumentsList
-
构造函数的参数列表。
newTarget
-
最初调用的构造函数。
返回值
描述
拦截
¥Interceptions
该陷阱可以拦截以下操作:
¥This trap can intercept these operations:
new
运算符:new myFunction(...args)
Reflect.construct()
或调用 [[Construct]]
内部方法 的任何其他操作。
¥Or any other operation that invokes the [[Construct]]
internal method.
不变量
示例
捕获新运算符
¥Trapping the new operator
以下代码捕获 new
运算符。
¥The following code traps the new
operator.
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.
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.
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 |
浏览器兼容性
BCD tables only load in the browser
也可以看看
¥See also