handler.ownKeys()
handler.ownKeys()
メソッドは Reflect.ownKeys()
に対するトラップです。
試してみましょう
構文
const p = new Proxy(target, { ownKeys: function(target) { } });
引数
次の引数は ownKeys
メソッドに渡されます。 this
はハンドラーにバインドされます。
target
-
ターゲットオブジェクトです。
返値
ownKeys()
メソッドは列挙可能オブジェクトを返さなければなりません。
解説
handler.ownKeys()
メソッドは Reflect.ownKeys()
に対するトラップです。
介入
このトラップは下記の操作に介入できます。
不変条件
例
getOwnPropertyNames のトラップ
次のコードでは Object.getOwnPropertyNames()
をトラップします。
const p = new Proxy({}, {
ownKeys: function(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: function(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