JavaScript 中的 handler.construct() 方法与 Proxy 对象结合使用,它允许您为对象上的基本操作定义自定义行为。当您将 Proxy 对象用作构造函数时,将调用此方法。在 Proxy 对象的帮助下,您可以封装另一个对象并使用它来拦截和修改其操作。
Handler.construct() 允许你修改有关代理对象实例如何构建的所有内容,包括添加更多初始化逻辑、添加日志记录,甚至完全更改行为。
语法
以下是 JavaScript handler.construct() 方法的语法 -
const p = new Proxy(target, {
construct: function(target, argumentsList, 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
在以下示例中,我们将向构造函数添加其他 logic。
<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>
当我们执行上述脚本时,会弹出输出窗口,在网页上显示文本。