Reflect.setPrototypeOf() 方法允许您设置对象的原型。它是 Reflect API 的一部分,后者提供了许多用于执行元编程任务的静态方法,例如属性操作和属性操作的拦截。
如果要修改现有对象的原型,可以使用 Reflect.setPrototypeOf() 方法。如果要创建从特定原型继承的对象,或者要扩展或修改对象的行为,这可能很有用。
语法
以下是 JavaScript Reflect.setPrototypeOf() 方法的语法 -
Reflect.setPrototypeOf(target, prototype)
参数
此方法接受两个参数。相同的描述如下 -
- target - 要设置属性的对象。
- prototype − 它保存对象 new prototype。它可以是任何对象或 null。
返回值
此方法返回 Boolean 值,该值指示原型是否已成功设置。
示例 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
在以下示例中,我们将 prototype 设置为 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>
在运行上述脚本时,它将生成一个包含网页上显示的文本的输出。