Reflect.has()

Baseline 已广泛支持

此特性已非常成熟,可在多种设备和浏览器版本上使用。自 ⁨2016 年 9 月⁩以来,它已在各大浏览器中可用。

Reflect.has() 静态方法类似于 in 操作符,但它是以函数形式存在的。

试一试

const object = {
  property1: 42,
};

console.log(Reflect.has(object, "property1"));
// Expected output: true

console.log(Reflect.has(object, "property2"));
// Expected output: false

console.log(Reflect.has(object, "toString"));
// Expected output: true

语法

js
Reflect.has(target, propertyKey)

参数

目标

要在其中查找属性的目标对象。

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"); // true
Reflect.has({ x: 0 }, "y"); // false

// returns true for properties in the prototype chain
Reflect.has({ x: 0 }, "toString");

// Proxy with .has() handler method
obj = new Proxy(
  {},
  {
    has(t, k) {
      return k.startsWith("door");
    },
  },
);
Reflect.has(obj, "doorbell"); // true
Reflect.has(obj, "dormitory"); // false

对于任何继承的属性,Reflect.has 都会返回 true,就像 in 操作符一样

js
const a = { foo: 123 };
const b = { __proto__: a };
const c = { __proto__: b };
// The prototype chain is: c -> b -> a
Reflect.has(c, "foo"); // true

规范

规范
ECMAScript® 2026 语言规范
# sec-reflect.has

浏览器兼容性

另见