handler.ownKeys()
Baseline Widely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since September 2016.
handler.ownKeys()
方法用于拦截 Reflect.ownKeys()
.
尝试一下
const monster1 = {
_age: 111,
[Symbol("secret")]: "I am scared!",
eyeCount: 4,
};
const handler1 = {
ownKeys(target) {
return Reflect.ownKeys(target);
},
};
const proxy1 = new Proxy(monster1, handler1);
for (const key of Object.keys(proxy1)) {
console.log(key);
// Expected output: "_age"
// Expected output: "eyeCount"
}
语法
js
var p = new Proxy(target, {
ownKeys: function (target) {},
});
参数
下面的参数被传递给 ownKeys。this
被绑定在 handler
上。
target
-
目标对象。
返回值
ownKeys
方法必须返回一个可枚举对象。
描述
handler.ownKeys()
方法用于拦截 Reflect.ownKeys()
.
拦截
约束
示例
下面的代码拦截 Object.getOwnPropertyNames()
.
js
var p = new Proxy(
{},
{
ownKeys: function (target) {
console.log("called");
return ["a", "b", "c"];
},
},
);
console.log(Object.getOwnPropertyNames(p)); // "called"; outputs [ 'a', 'b', 'c' ]
下面的代码违反了约定
js
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]] 必须返回一个数组
// 数组元素类型只能是 String 或 Symbol
规范
Specification |
---|
ECMAScript® 2025 Language Specification # sec-proxy-object-internal-methods-and-internal-slots-ownpropertykeys |
浏览器兼容性
BCD tables only load in the browser