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 September 2016.

Die Reflect.has() statische Methode ist wie der in Operator, jedoch als Funktion.

Probieren Sie es aus

const object1 = {
  property1: 42,
};

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

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

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

Syntax

js
Reflect.has(target, propertyKey)

Parameter

target

Das Zielobjekt, in dem nach der Eigenschaft gesucht wird.

propertyKey

Der Name der zu prüfenden Eigenschaft.

Rückgabewert

Ein Boolean, der angibt, ob das target die Eigenschaft hat oder nicht.

Ausnahmen

TypeError

Wird ausgelöst, wenn target kein Objekt ist.

Beschreibung

Reflect.has() bietet die reflektive Semantik zur Prüfung, ob eine Eigenschaft in einem Objekt vorhanden ist. Das bedeutet, Reflect.has(target, propertyKey) ist semantisch gleichwertig mit:

js
propertyKey in target;

Reflect.has() ruft die [[HasProperty]] interne Objekte-Methode des target auf.

Beispiele

Verwendung von 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 gibt true für alle geerbten Eigenschaften zurück, wie der in Operator:

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

Spezifikationen

Specification
ECMAScript® 2026 Language Specification
# sec-reflect.has

Browser-Kompatibilität

Siehe auch