JavaScript 中的 handler.setPrototypeOf() 方法允许您将指定对象的原型设置为另一个对象,再设置另一个对象。此方法允许您修改对象的原型,从而有效地更改其继承链。您可以使用它来动态更改对象在代码中的行为方式。但是,请务必谨慎使用此方法,因为如果使用不当,可能会导致意外行为。此方法也是 Proxy 对象处理程序的一部分,它允许您通过为 Proxy 对象提供陷阱来修改 Proxy 对象的行为。
语法
以下是 JavaScript handler.setPrototypeOf() 方法的语法 -
new Proxy(target, {
setPrototypeOf(target, prototype) {}
});
参数
- target − 它保存目标对象。
- prototype − 它是对象 new prototype 或 null。
返回值
此方法返回一个 布尔值 (Boolean Value) ,如果原型已成功更改,则返回 true。
示例 1
让我们看看下面的例子,我们将更改对象的原型。
<html>
<style>
body {
font-family: verdana;
color: #DE3163;
}
</style>
<body>
<script>
const x = {};
const y = {
a: 10
};
const z = {
setPrototypeOf(target, prototype) {
return Reflect.setPrototypeOf(target, prototype);
}
};
const b = new Proxy(x, z);
z.setPrototypeOf(b, y);
document.write(b.a);
</script>
</body>
</html>
输出
如果我们执行上述程序,它将在网页上显示文本。
示例 2
考虑另一个场景,我们将阻止原型更改。
<html>
<style>
body {
font-family: verdana;
color: #DE3163;
}
</style>
<body>
<script>
const x = {};
const y = {
a: 10
};
const z = {
setPrototypeOf(target, prototype) {
console.error("Prototype setting is not allowed");
return false;
}
};
const b = new Proxy(x, z);
z.setPrototypeOf(b, y);
document.write(b.a);
</script>
</body>
</html>
输出
在执行上述脚本时,它将在网页上显示文本。
示例 3
在下面的示例中,每当对象发生更改时,我们将记录原型更改。
<html>
<style>
body {
font-family: verdana;
color: #DE3163;
}
</style>
<body>
<script>
const a = {};
const b = {
setPrototypeOf(target, proto) {
document.write("Prototype changed to: " + JSON.stringify(d));
return Reflect.setPrototypeOf(target, proto);
}
};
const c = new Proxy(a, b);
const d = {
x: 'WELCOME'
};
Object.setPrototypeOf(c, d);
</script>
</body>
</html>
当我们执行上述代码时,它将生成一个由网页上显示的文本组成的输出。