試一試
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 |
瀏覽器相容性
載入中…