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
语法
参数
¥Parameters
以下参数传递给 ownKeys()
方法。this
绑定到处理程序。
¥The following parameter is passed to the ownKeys()
method. this
is bound to the handler.
target
-
目标对象。
返回值
描述
拦截
¥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
。 - 键列表不包含重复值。
- 每个键的类型是
String
或Symbol
。 - 结果列表必须包含目标对象的所有不可配置自有属性的键。也就是说,对于目标对象上
Reflect.ownKeys()
返回的所有键,如果键通过Reflect.getOwnPropertyDescriptor()
报告configurable: false
,则该键必须包含在结果列表中。 - 如果目标对象不可扩展,则结果列表必须包含目标对象自身属性的所有键,而不包含其他值。也就是说,如果
Reflect.isExtensible()
在target
上返回false
,则结果列表必须包含与Reflect.ownKeys()
在target
上的结果相同的值。
示例
getOwnPropertyNames 的捕获
¥Trapping of getOwnPropertyNames
以下代码捕获 Object.getOwnPropertyNames()
。
¥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 |
浏览器兼容性
BCD tables only load in the browser