handler.ownKeys()
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月.
handler.ownKeys()
メソッドは、オブジェクトの [[OwnPropertyKeys]]
内部メソッドに対するトラップです。 Object.keys()
, Reflect.ownKeys()
などの操作で使用されます。
試してみましょう
const monster = {
_age: 111,
[Symbol("secret")]: "I am scared!",
eyeCount: 4,
};
const handler = {
ownKeys(target) {
return Reflect.ownKeys(target);
},
};
const proxy = new Proxy(monster, handler);
for (const key of Object.keys(proxy)) {
console.log(key);
// 予想される結果: "_age"
// 予想される結果: "eyeCount"
}
構文
js
new Proxy(target, {
ownKeys(target) {
}
})
引数
次の引数は ownKeys()
メソッドに渡されます。 this
はハンドラーにバインドされます。
target
-
ターゲットオブジェクトです。
返値
ownKeys()
メソッドは 配列風オブジェクトを返す必要があります。それぞれの要素は String
または Symbol
であり、重複するアイテムを含んではいけません。
解説
>介入
このトラップは下記の操作に介入できます。
他にも、[[OwnPropertyKeys]]
内部メソッドを呼び出すあらゆる操作に介入できます。
不変条件
プロキシーの [[OwnPropertyKeys]]
内部メソッドでは、ハンドラー定義が以下の不変条件のいずれかに違反する場合、TypeError
が発生します。
- 結果が
Object
である。 - キーのリストには重複する値が含まれていない。
- それぞれのキーの型が
String
またはSymbol
のどちらかである。 - 結果リストには、ターゲットオブジェクトのすべての構成不可の自己プロパティのキーが含まれていなければならない。つまり、ターゲットオブジェクトに対して
Reflect.ownKeys()
が返すすべてのキーについて、そのキーがReflect.getOwnPropertyDescriptor()
によってconfigurable: false
を返す場合、そのキーは結果リストに含まれていなければならない。 - 対象オブジェクトが拡張不可の場合、結果リストには対象オブジェクトの自己プロパティのすべてのキーが含まれ、それ以外の値は含まれてはいけない。つまり、
Reflect.isExtensible()
がtarget
でfalse
を返す場合、結果リストにはReflect.ownKeys()
をtarget
に適用した結果と同じ値が含まれなければならない。
例
>getOwnPropertyNames のトラップ
次のコードでは Object.getOwnPropertyNames()
をトラップします。
js
const p = new Proxy(
{},
{
ownKeys(target) {
console.log("called");
return ["a", "b", "c"];
},
},
);
console.log(Object.getOwnPropertyNames(p));
// "called"
// [ 'a', 'b', 'c' ]
次のコードでは不変条件に違反します。
js
const obj = {};
Object.defineProperty(obj, "a", {
configurable: false,
enumerable: true,
value: 10,
});
const p = new Proxy(obj, {
ownKeys(target) {
return [123, 12.5, true, false, undefined, null, {}, []];
},
});
console.log(Object.getOwnPropertyNames(p));
// TypeError: proxy [[OwnPropertyKeys]] must return an array
// with only string and symbol elements
仕様書
Specification |
---|
ECMAScript® 2026 Language Specification> # sec-proxy-object-internal-methods-and-internal-slots-ownpropertykeys> |
ブラウザーの互換性
Loading…