Reflect.has() 方法用于确定目标对象是否具有特定属性。它类似于 Object.prototype.hasOwnProperty() 方法或 in 运算符,但它提供了一种更灵活、更一致的属性检查方法。Reflect.has() 方法不是一个函数,而是一个静态方法,因此您不应将其用作函数。
与 Object.prototype.hasOwnProperty() 相反,如果目标对象为 null 或未定义,则 Reflect.has() 不会引发错误。在某些情况下,它会返回 false。
语法
以下是 JavaScript Reflect.has() 方法的语法 -
Reflect.has(target, propertyKey)
参数
此方法接受两个参数。相同的描述如下 -
- target - 要获取属性的目标对象。
- propertyKey - 要检查的属性的名称。
返回值
此方法返回 Boolean 值,该值指示目标是否具有属性。
示例 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() 来检查是否存在 symbol 属性。
<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() 用于 Inherited Property。
<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>
在运行上述代码时,将弹出输出窗口,在网页上显示文本。