JavaScript - Reflect.setPrototypeOf() 方法
Reflect.setPrototypeOf() 方法允许您设置对象的原型。它是 Reflect API 的一部分,该 API 提供了许多静态方法用于执行元编程任务,例如属性操作和属性操作的拦截。
如果您想修改现有对象的原型,可以使用 Reflect.setPrototypeOf() 方法。当您想要创建从特定原型继承的对象,或者想要扩展或修改对象的行为时,这种方法非常有用。
语法
以下是 JavaScript Reflect.setPrototypeOf() 方法的语法 -
Reflect.setPrototypeOf(target, prototype)
参数
此方法接受两个参数。如下所示:-
target - 要设置属性的对象。
prototype - 它保存对象的新原型。它可以是任何对象或 null。
返回值
此方法返回布尔值,指示原型是否已成功设置。
示例
示例 1
让我们看下面的示例,我们将在其中设置对象的原型。
<html>
<style>
body {
font-family: verdana;
color: #DE3163;
}
</style>
<body>
<script>
const x = {};
const y = {
a: 10
};
Reflect.setPrototypeOf(x, y);
document.write(x.a);
</script>
</body>
</html>
如果我们执行上述程序,它将在网页上显示一个数字。
示例 2
考虑另一种情况,我们将要更改现有对象的原型。
<html>
<style>
body {
font-family: verdana;
color: #DE3163;
}
</style>
<body>
<script>
const x = {
a: 22
};
const y = {
b: 123
};
Reflect.setPrototypeOf(x, y);
document.write(x.b);
</script>
</body>
</html>
执行上述脚本后,网页上将显示一个数字。
示例 3
在下面的示例中,我们将原型设置为 null。
<html>
<style>
body {
font-family: verdana;
color: #DE3163;
}
</style>
<body>
<script>
const x = {};
Reflect.setPrototypeOf(x, null);
document.write(Object.getPrototypeOf(x));
</script>
</body>
</html>
执行上述脚本后,输出窗口将会弹出,并在网页上显示文本。
示例 4
以下示例将检查对象是否继承自原型。
<html>
<style>
body {
font-family: verdana;
color: #DE3163;
}
</style>
<body>
<script>
let x = {
a: 11
};
let y = {};
Reflect.setPrototypeOf(y, x);
document.write(Reflect.getPrototypeOf(y) === x);
</script>
</body>
</html>
运行上述脚本后,它将生成由网页上显示的文本组成的输出。

