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.
不变量
示例
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