The handler.ownKeys()
method is a trap for the [[OwnPropertyKeys]]
object internal method, which is used by operations such as Object.keys()
, Reflect.ownKeys()
, etc.
The handler.ownKeys()
method is a trap for the [[OwnPropertyKeys]]
object internal method, which is used by operations such as Object.keys()
, Reflect.ownKeys()
, etc.
new Proxy(target, { ownKeys(target) { } });
The following parameter is passed to the ownKeys()
method. this
is bound to the handler.
target
The target object.
The ownKeys()
method must return an enumerable object.
This trap can intercept these operations:
Or any other operation that invokes the [[OwnPropertyKeys]]
internal method.
If the following invariants are violated, the trap throws a TypeError
when invoked.
ownKeys()
must be an array.String
or a Symbol
. The following code traps Object.getOwnPropertyNames()
.
const p = new Proxy( {}, { ownKeys(target) { console.log("called"); return ["a", "b", "c"]; }, }, ); console.log(Object.getOwnPropertyNames(p)); // "called" // [ 'a', 'b', 'c' ]
The following code violates an invariant.
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 |
Desktop | Mobile | Server | ||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
Chrome | Edge | Firefox | Opera | Safari | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | WebView Android | Deno | Node.js | ||
ownKeys |
49 | 12 | 18In Firefox 42, the implementation got updated to reflect the final ES2015 specification: The result is now checked if it is an array and if the array elements are either of type string or of type symbol. Enumerating duplicate own property names is not a failure anymore. |
36 | 10 | 49 | 18In Firefox 42, the implementation got updated to reflect the final ES2015 specification: The result is now checked if it is an array and if the array elements are either of type string or of type symbol. Enumerating duplicate own property names is not a failure anymore. |
36 | 10 | 5.0 | 49 | 1.0 | 6.0.0 |
© 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy/Proxy/ownKeys