在 JavaScript 中,代理对象可以利用 handler.getPrototypeOf() 来拦截对 Object.getPrototypeOf() 的调用。它允许自定义原型检索行为。处理程序 getPrototypeOf() 在访问对象的原型时调用。这实现了对原型访问的动态控制,从而促进了虚拟化和封装等功能。如果处理程序未定义 getPrototypeOf(),则执行默认原型查找。此方法对于包含继承和对象组合等功能至关重要。
语法
以下是 JavaScript handler.getPrototypeOf() 方法的语法 -
new Proxy(obj, {
getPrototypeOf(target) {
// …
}
});
参数
- target − 它保存目标对象。
返回值
此方法返回一个 object,如果 no no 则返回 null,未返回对象。
示例 1
让我们看看下面的例子,我们将使用 handler.getPrototypeOf() 来检索代理对象的原型。
<html>
<style>
body {
font-family: verdana;
color: #DE3163;
}
</style>
<body>
<script>
const x = {};
const y = {
getPrototypeOf(target) {
return Object.getPrototypeOf(target);
}
};
const z = new Proxy(x, y);
document.write(y.getPrototypeOf(z) === Object.getPrototypeOf(z));
</script>
</body>
</html>
输出
如果我们执行上述程序,它将在网页上显示文本。
示例 2
考虑另一个场景,我们将阻止访问目标对象的原型。
<html>
<style>
body {
font-family: verdana;
color: #DE3163;
}
</style>
<body>
<script>
const x = {};
const y = {
getPrototypeOf: function(target) {
return null;
}
};
const z = new Proxy(x, y);
document.write(Object.getPrototypeOf(z));
</script>
</body>
</html>
输出
在执行上述脚本时,它将在网页上显示 null 文本。
示例 3
在下面的示例中,我们将使用 handler.getPrototypeOf() 将代理对象的原型动态调整为 Array.prototype。
<html>
<style>
body {
font-family: verdana;
color: #DE3163;
}
</style>
<body>
<script>
const x = {};
const y = {
getPrototypeOf(target) {
return Array.prototype;
}
};
const z = new Proxy(x, y);
document.write(y.getPrototypeOf(z) === Array.prototype);
</script>
</body>
</html>
当我们执行上述代码时,它将生成一个由网页上显示的文本组成的输出。