Reflect.getPrototypeOf() 方法用于返回对象的原型。它类似于 Object.getPrototypeOf() 方法,但它是 Reflect 对象的一部分,该对象提供了一组用于对对象执行元操作的方法。
使用 Reflect.getPrototypeOf() 方法的主要优点是它与 Proxy API 结合使用。它可以帮助您拦截和修改对对象的操作,包括检索原型。该方法为 JavaScript 操作提供了反射 API,增强了语言的自省能力。
语法
以下是 JavaScript Reflect.getPrototypeOf() 方法的语法 -
Reflect.getPrototypeOf(obj)
参数
此方法只接受一个参数。相同的描述如下 -
- obj - 要检索其原型的对象。
返回值
此方法返回给定对象的原型。
示例 1
让我们看看下面的例子,我们将使用 Reflect.getPrototypeOf() 来检索空对象的原型。
<html>
<style>
body {
font-family: verdana;
color: #DE3163;
}
</style>
<body>
<script>
const x = {};
const prototype = Reflect.getPrototypeOf(x);
document.write(prototype);
</script>
</body>
</html>
如果我们执行上述程序,它将在网页上显示文本。
示例 2
考虑另一个场景,我们将使用对象字面量并创建一个对象。
<html>
<style>
body {
font-family: verdana;
color: #DE3163;
}
</style>
<body>
<script>
let x = {
car: 'RS6'
};
document.write(Reflect.getPrototypeOf(x) === Object.prototype);
</script>
</body>
</html>
在执行上述脚本时,它将在网页上显示文本。
示例 3
在下面的示例中,我们将获取数组的原型。
<html>
<style>
body {
font-family: verdana;
color: #DE3163;
}
</style>
<body>
<script>
const x = [11, 22, 33];
const prototype = Reflect.getPrototypeOf(x);
document.write(JSON.stringify(prototype));
</script>
</body>
</html>
当我们执行上述脚本时,会弹出输出窗口,在网页上显示文本。