此页面由社区从英文翻译而来。了解更多并加入 MDN Web Docs 社区。
Reflect.has()
Baseline Widely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since 2016年9月.
Reflect.has() 静态方法的作用类似于in 运算符,但它以函数的形式实现。
In this article
尝试一下
const object = { property1: 42,};console.log(Reflect.has(object, "property1"));// 期望输出:trueconsole.log(Reflect.has(object, "property2"));// 期望输出:falseconsole.log(Reflect.has(object, "toString"));// 期望输出:true语法
js
Reflect.has(target, propertyKey)参数
target要查找该属性的目标对象。
propertyKey要检测的属性名称。
返回值
Boolean,表示target 是否具有该属性。
异常
TypeError如果
target不是对象,则抛出此异常。
描述
Reflect.has() 提供了一种用于检查属性是否存在于对象中的反射语义。也就是说,Reflect.has(target, propertyKey) 在语义上等价于:
js
propertyKey in target;Reflect.has() 会调用target 的[[HasProperty]]对象内部方法。
示例
>使用 Reflect.has()
js
Reflect.has({ x: 0 }, "x"); // trueReflect.has({ x: 0 }, "y"); // false// 对原型链上的属性也会返回 trueReflect.has({ x: 0 }, "toString");// 带有 .has() 处理器方法的 Proxyobj = new Proxy( {}, { has(t, k) { return k.startsWith("door"); }, },);Reflect.has(obj, "doorbell"); // trueReflect.has(obj, "dormitory"); // falseReflect.has 会对任何继承的属性返回true,这一点与in 运算符相同:
js
const a = { foo: 123 };const b = { __proto__: a };const c = { __proto__: b };// 原型链为:c -> b -> aReflect.has(c, "foo"); // true规范
| Specification |
|---|
| ECMAScript® 2026 Language Specification> # sec-reflect.has> |