Reflect.getOwnPropertyDescriptor()
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.getOwnPropertyDescriptor() は静的メソッドで、Object.getOwnPropertyDescriptor() と似ています。オブジェクトに指定されたプロパティが存在する場合、そのプロパティ記述子を返します。存在しない場合は undefined を返します。
試してみましょう
const object = {
property1: 42,
};
console.log(Reflect.getOwnPropertyDescriptor(object, "property1").value);
// 予想される結果: 42
console.log(Reflect.getOwnPropertyDescriptor(object, "property2"));
// 予想される結果: undefined
console.log(Reflect.getOwnPropertyDescriptor(object, "property1").writable);
// 予想される結果: true
構文
Reflect.getOwnPropertyDescriptor(target, propertyKey)
引数
target-
プロパティを探す対象のオブジェクト。
propertyKey-
所有しているプロパティ記述子を取得するためのプロパティ名。
返値
target オブジェクト内にプロパティが存在する場合は、プロパティ記述子オブジェクト、または undefined。
例外
TypeError-
targetがオブジェクトではない場合
解説
Reflect.getOwnPropertyDescriptor() は、オブジェクトのプロパティ記述子を取得する反射的意味づけを提供します。Object.getOwnPropertyDescriptor() との唯一の違いは、オブジェクト以外の対象の処理方法です。Reflect.getOwnPropertyDescriptor() は対象がオブジェクトでない場合に TypeError を発生しますが、Object.getOwnPropertyDescriptor() はそれをオブジェクトに変換します。
Reflect.getOwnPropertyDescriptor() は、target の [[GetOwnProperty]] オブジェクト内部メソッド を呼び出します。
例
>Reflect.getOwnPropertyDescriptor() の使用
Reflect.getOwnPropertyDescriptor({ x: "hello" }, "x");
// {value: "hello", writable: true, enumerable: true, configurable: true}
Reflect.getOwnPropertyDescriptor({ x: "hello" }, "y");
// undefined
Reflect.getOwnPropertyDescriptor([], "length");
// {value: 0, writable: true, enumerable: false, configurable: false}
Object.getOwnPropertyDescriptor() との違い
このメソッドへの最初の引数がオブジェクトではない (プリミティブであった) 場合、 TypeError が発生します。 Object.getOwnPropertyDescriptor だと、非オブジェクトである最初の引数は強制的にオブジェクトに変換されます。
Reflect.getOwnPropertyDescriptor("foo", 0);
// TypeError: "foo" is not non-null object
Object.getOwnPropertyDescriptor("foo", 0);
// { value: "f", writable: false, enumerable: true, configurable: false }
仕様書
| Specification |
|---|
| ECMAScript® 2026 Language Specification> # sec-reflect.getownpropertydescriptor> |