handler.ownKeys()

handler.ownKeys() メソッドは、オブジェクトの [[OwnPropertyKeys]] 内部メソッドに対するトラップです。 Object.keys(), Reflect.ownKeys() などの操作で使用されます。

試してみましょう

構文

js
new Proxy(target, {
  ownKeys(target) {
  }
});

引数

次の引数は ownKeys() メソッドに渡されます。 this はハンドラーにバインドされます。

target

ターゲットオブジェクトです。

返値

ownKeys() メソッドは列挙可能オブジェクトを返さなければなりません。

解説

介入

このトラップは下記の操作に介入できます。

他にも、[[OwnPropertyKeys]] 内部メソッドを呼び出すあらゆる操作に介入できます。

不変条件

以下の不変条件に違反している場合、プロキシーは TypeError を発生します。

  • ownKeys() の結果は配列である必要があります。
  • 配列のそれぞれの要素の型は、String または Symbol のどちらかです。
  • 結果のリストはターゲットオブジェクトのすべての非設定の独自プロパティのキーを含みます。
  • ターゲットオブジェクトが拡張可能でないなら、結果リストはターゲットオブジェクトのすべての独自プロパティのキーを含まなければなりません。そして、他の値を含みません。

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 Language Specification
# sec-proxy-object-internal-methods-and-internal-slots-ownpropertykeys

ブラウザーの互換性

BCD tables only load in the browser

関連情報