handler.ownKeys()

handler.ownKeys() 方法是对 [[OwnPropertyKeys]] 对象内部方法 的陷阱,被 Object.keys()Reflect.ownKeys() 等操作使用。

¥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.

Try it

语法

¥Syntax

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

参数

¥Parameters

以下参数传递给 ownKeys() 方法。this 绑定到处理程序。

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

target

目标对象。

返回值

¥Return value

ownKeys() 方法必须返回一个 类似数组的对象,其中每个元素都是不包含重复项的 StringSymbol

¥The ownKeys() method must return an array-like object where each element is either a String or a Symbol containing no duplicate items.

描述

¥Description

拦截

¥Interceptions

该陷阱可以拦截以下操作:

¥This trap can intercept these operations:

或调用 [[OwnPropertyKeys]] 内部方法 的任何其他操作。

¥Or any other operation that invokes the [[OwnPropertyKeys]] internal method.

不变量

¥Invariants

如果处理程序定义违反以下不变量之一,则代理的 [[OwnPropertyKeys]] 内部方法将抛出 TypeError

¥The proxy's [[OwnPropertyKeys]] internal method throws a TypeError if the handler definition violates one of the following invariants:

  • 结果是 Object
  • 键列表不包含重复值。
  • 每个键的类型是 StringSymbol
  • 结果列表必须包含目标对象的所有不可配置自有属性的键。也就是说,对于目标对象上 Reflect.ownKeys() 返回的所有键,如果键通过 Reflect.getOwnPropertyDescriptor() 报告 configurable: false,则该键必须包含在结果列表中。
  • 如果目标对象不可扩展,则结果列表必须包含目标对象自身属性的所有键,而不包含其他值。也就是说,如果 Reflect.isExtensible()target 上返回 false,则结果列表必须包含与 Reflect.ownKeys()target 上的结果相同的值。

示例

¥Examples

getOwnPropertyNames 的捕获

¥Trapping of getOwnPropertyNames

以下代码捕获 Object.getOwnPropertyNames()

¥The following code traps 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' ]

以下代码违反了不变量。

¥The following code violates an invariant.

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

¥Specifications

浏览器兼容性

BCD tables only load in the browser

¥Browser compatibility

也可以看看