A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Global_Objects/Proxy/Proxy/ownKeys below:

handler.ownKeys() - JavaScript | MDN

handler.ownKeys()

Baseline Widely available

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

試してみましょう
const monster1 = {
  _age: 111,
  [Symbol("secret")]: "I am scared!",
  eyeCount: 4,
};

const handler1 = {
  ownKeys(target) {
    return Reflect.ownKeys(target);
  },
};

const proxy1 = new Proxy(monster1, handler1);

for (const key of Object.keys(proxy1)) {
  console.log(key);
  // Expected output: "_age"
  // Expected output: "eyeCount"
}
構文
new Proxy(target, {
  ownKeys(target) {
  }
});
引数

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

target

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

返値

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

解説 介入

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

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

不変条件

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

例 getOwnPropertyNames のトラップ

次のコードでは Object.getOwnPropertyNames() をトラップします。

const p = new Proxy(
  {},
  {
    ownKeys(target) {
      console.log("called");
      return ["a", "b", "c"];
    },
  },
);

console.log(Object.getOwnPropertyNames(p));
// "called"
// [ 'a', 'b', 'c' ]

次のコードでは不変条件に違反します。

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
仕様書 ブラウザーの互換性 関連情報

RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4