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() 方法必须返回一个可枚举对象。

¥The ownKeys() method must return an enumerable object.

描述

¥Description

拦截

¥Interceptions

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

¥This trap can intercept these operations:

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

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

不变量

¥Invariants

如果违反以下不变量,则陷阱在调用时会抛出 TypeError

¥If the following invariants are violated, the trap throws a TypeError when invoked.

  • ownKeys() 的结果必须是一个数组。
  • 每个数组元素的类型是 StringSymbol
  • 结果 List 必须包含目标对象所有不可配置的自身属性的键。
  • 如果目标对象不可扩展,则结果 List 必须包含目标对象自身属性的所有键,并且不包含其他值。

示例

¥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

也可以看看