Please note, this is a STATIC archive of website developer.mozilla.org from November 2016, cach3.com does not collect or store any user information, there is no "phishing" involved.

handler.ownKeys()

我们的志愿者还没有将这篇文章翻译为 中文 (简体)加入我们帮助完成翻译!

The handler.ownKeys() method is a trap for Object.getOwnPropertyNames().

Syntax

var p = new Proxy(target, {
  ownKeys: function(target) {
  }
});

Parameters

The following parameter is passed to the ownKeys method. this is bound to the handler.

target
The target object.

Return value

The ownKeys method must return an enumerable object.

Description

The handler.ownKeys() method is a trap for Object.getOwnPropertyNames().

Interceptions

This trap can intercept these operations:

Invariants

If the following invariants are violated, the proxy will throw a TypeError:

  • The result of ownKeys must be an array.
  • The type of each array element is either a String or a Symbol.
  • The result List must contain the keys of all non-configurable own properties of the target object.
  • If the target object is not extensible, then the result List must contain all the keys of the own properties of the target object and no other values.

Examples

The following code traps Object.getOwnPropertyNames().

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

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

The following code violates an invariant.

var obj = {};
Object.defineProperty(obj, "a", { 
  configurable: false, 
  enumerable: true, 
  value: 10 }
);

var 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

Specifications

Specification Status Comment
ECMAScript 2015 (6th Edition, ECMA-262)
The definition of '[[OwnPropertyKeys]]' in that specification.
Standard Initial definition.
ECMAScript 2017 Draft (ECMA-262)
The definition of '[[OwnPropertyKeys]]' in that specification.
Draft  

Browser compatibility

Feature Chrome Firefox (Gecko) Internet Explorer Opera Safari
Basic support ? 18 (18) ? ? ?
Feature Android Chrome for Android Firefox Mobile (Gecko) IE Mobile Opera Mobile Safari Mobile
Basic support ? ? 18.0 (18) ? ? ?

Compatibility notes

Firefox

  • In Gecko 42 (Firefox 42 / Thunderbird 42 / SeaMonkey 2.39), the ownKey implementation got updated to reflect the final ES2015 specification (see bug 1049662):
    • 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.

See also

文档标签和贡献者

 此页面的贡献者: m31271n_, fscholz, slavede, arai
 最后编辑者: m31271n_,