JavaScript - Reflect.has() 方法
Reflect.has() 方法用于判断目标对象是否具有特定属性。它类似于 Object.prototype.hasOwnProperty() 方法或 in 运算符,但它提供了一种更灵活、更一致的属性检查方法。Reflect.has() 方法不是函数,而是一个静态方法,因此不应将其用作函数。
与 Object.prototype.hasOwnProperty() 不同,如果目标对象为 null 或 undefined,Reflect.has() 不会引发错误。在某些情况下,它会返回 false。
语法
以下是 JavaScript Reflect.has() 方法的语法 -
Reflect.has(target, propertyKey)
参数
此方法接受两个参数。下文将分别介绍 -
target - 要获取属性的目标对象。
propertyKey - 要检查的属性名称。
返回值
此方法返回布尔值,指示目标是否具有属性。
示例
示例 1
让我们看下面的示例,我们将使用 Reflect.has() 来检查对象是否具有属性。
<html>
<style>
body {
font-family: verdana;
color: #DE3163;
}
</style>
<body>
<script>
const x = {
car: 'BMW',
Model: 2018
};
document.write(Reflect.has(x, 'Model') + " < br > ");
document.write(Reflect.has(x, 'spare'));
</script>
</body>
</html>
如果我们执行上述程序,它将在网页上显示一段文本。
示例 2
考虑另一种场景,我们将 configurable 设置为 false,并尝试删除该属性,并使用 Reflect.has() 检索输出。
<html>
<style>
body {
font-family: verdana;
color: #DE3163;
}
</style>
<body>
<script>
const x = {};
Object.defineProperty(x, 'Bike', {
value: 'Rx100',
configurable: false
});
delete x.Bike;
document.write(Reflect.has(x, 'Bike'));
</script>
</body>
</html>
执行上述脚本后,网页上将显示一段文本。
示例 3
在下面的示例中,我们将使用 Reflect.has() 来检查符号属性是否存在。
<html>
<style>
body {
font-family: verdana;
color: #DE3163;
}
</style>
<body>
<script>
const x = Symbol('Tp');
const y = {
[x]: 'Welcome'
};
document.write(Reflect.has(y, x));
</script>
</body>
</html>
执行上述脚本后,输出窗口将会弹出,并在网页上显示文本。
示例 4
以下示例将使用 Reflect.has() 来处理继承属性。
<html>
<style>
body {
font-family: verdana;
color: #DE3163;
}
</style>
<body>
<script>
class x {
constructor() {
this.a = 11;
}
}
class y extends x {
constructor() {
super();
this.b = 22;
}
}
const z = new y();
document.write(Reflect.has(z, 'a'));
</script>
</body>
</html>
运行上述代码后,将弹出输出窗口,在网页上显示文本。

