JavaScript - Reflect.get() 方法
Reflect.get() 方法是 Reflect API 的一部分,它提供了一组静态方法,用于对对象执行类似于运算符的操作。此方法用于检索对象的属性值,类似于点操作或括号操作,但具有额外的特性和灵活性。
语法
以下是 JavaScript Reflect.get() 方法的语法 -
Reflect.get(target, propertyKey, receiver)
参数
此方法接受三个参数。下文将分别介绍 -
target - 要获取属性的目标对象。
propertyKey - 要获取的属性名称。
receiver - 可选参数,是调用 target 时提供的 this 值。
返回值
此方法返回属性的值。
示例
示例 1
让我们看下面的示例,我们将使用 Reflect.get() 并检索属性的值。
<html>
<style>
body {
font-family: verdana;
color: #DE3163;
}
</style>
<body>
<script>
const x = {
car: 'Maserati',
model: 2024
};
const y = Reflect.get(x, 'car');
document.write(JSON.stringify(y));
</script>
</body>
</html>
如果我们执行上述程序,它将在网页上显示一段文本。
示例 2
考虑另一种场景,我们将使用以符号定义的 Reflect.get() 来访问属性。
<html>
<style>
body {
font-family: verdana;
color: #DE3163;
}
</style>
<body>
<script>
const x = Symbol('tp');
const y = {
[x]: 'TutorialsPoint'
};
const z = Reflect.get(y, x);
document.write(z);
</script>
</body>
</html>
执行上述脚本后,网页上将显示一段文本。
示例 3
在下面的示例中,我们将访问不存在的属性并检查输出。
<html>
<style>
body {
font-family: verdana;
color: #DE3163;
}
</style>
<body>
<script>
const x = {
state: 'Telangana',
capital: 'Hyderabad'
};
const y = Reflect.get(x, 'population');
document.write(y);
</script>
</body>
</html>
当我们执行上述脚本时,会弹出输出窗口,显示网页上的文本。

