JavaScript Handler construct() 方法
JavaScript 中的 handler.construct() 方法与 Proxy 对象结合使用,允许您为对象的基本操作定义自定义行为。当您将 Proxy 对象用作构造函数时,会调用此方法。借助 Proxy 对象,您可以封装另一个对象,并使用它来拦截和修改其操作。
Handler.construct() 允许您修改代理对象实例的构造方式,包括添加更多初始化逻辑、添加日志记录,甚至完全更改其行为。
语法
以下是 JavaScript handler.construct() 方法的语法 -
const p = new Proxy(target, {
construct: function(target, argumentList, newTarget) {}
});
参数
- target − 保存目标对象。
- argumentsList − 构造函数的 this 参数。
- newTarget − 保存最初调用的构造函数。
返回值
此方法返回一个对象。
示例 1
让我们看下面的示例,我们将在创建实际实例之前记录类的新实例的创建过程。
<html>
<style>
body {
font-family: verdana;
color: #DE3163;
}
</style>
<body>
<script>
const examp = {
construct(x, y) {
document.write(`Creating new instance of ${x.name}`);
return new x(...y);
}
};
class tp {
constructor(name) {
this.name = name;
}
}
const a = new Proxy(tp, examp);
const b = new a('Welcome');
</script>
</body>
</html>
输出
如果我们执行上述程序,它将在网页上显示一段文本。
示例 2
考虑另一种场景,我们将检查是否只创建了一个类的实例,并在后续调用时返回相同的实例。
<html>
<style>
body {
font-family: verdana;
color: #DE3163;
}
</style>
<body>
<script>
const examp = {
construct(x, y) {
if (!x.instance) {
x.instance = new x(...y);
}
return x.instance;
}
};
class tp {}
const a = new Proxy(tp, examp);
const x1 = new a();
const x2 = new a();
document.write(x1 === x2);
</script>
</body>
</html>
输出
执行上述脚本后,网页上将显示一段文本。
示例 3
在下面的示例中,我们将向构造函数添加附加逻辑。
<html>
<style>
body {
font-family: verdana;
color: #DE3163;
}
</style>
<body>
<script>
function bike(x, y) {
this.x = x;
this.y = y;
this.fullName = function() {
return this.x + ' ' + this.y;
};
}
const examp = {
construct(a, b) {
const z = new a(...b);
z.year = new Date().getFullYear();
return z;
}
};
const c = new Proxy(bike, examp);
const d = new c("Vespa", "Bullet");
document.write(d.fullName() + " < br > ");
document.write(d.year);
</script>
</body>
</html>
当我们执行上述脚本时,会弹出输出窗口,显示网页上的文本。

