handler.ownKeys() 方法用于拦截 Reflect.ownKeys().
语法
var p = new Proxy(target, {
ownKeys: function(target) {
}
});
参数
下面的参数被传递给ownKeys。this被绑定在handler上。
-
target - 目标对象.
返回值
ownKeys 方法必须返回一个可枚举对象.
描述
handler.ownKeys() 方法用于拦截 Reflect.ownKeys().
拦截
该拦截器可以拦截以下操作::
约束
如果违反了下面的约束,proxy将抛出错误 TypeError:
ownKeys的结果必须是一个数组.- 数组的元素类型要么是一个
Symbol. - 结果列表必须包含目标对象的所有不可配置(non-configurable )、自有(own)属性的key.
- 如果目标对象不可扩展,那么结果列表必须包含目标对象的所有自有(own)属性的key,不能有其它值.
示例
下面的代码拦截 Object.getOwnPropertyNames().
var p = new Proxy({}, {
ownKeys: function(target) {
console.log('called');
return ['a', 'b', 'c'];
}
});
console.log(Object.getOwnPropertyNames(p)); // "called"
// [ 'a', 'b', 'c' ]
下面的代码违反了约定
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 | Status | Comment |
|---|---|---|
| ECMAScript 2015 (6th Edition, ECMA-262) [[OwnPropertyKeys]] |
Standard | Initial definition. |
| ECMAScript Latest Draft (ECMA-262) [[OwnPropertyKeys]] |
Draft |
浏览器兼容
We're converting our compatibility data into a machine-readable JSON format. This compatibility table still uses the old format, because we haven't yet converted the data it contains.
Find out how you can help!
| Feature | Chrome | Firefox (Gecko) | Internet Explorer | Opera | Safari |
|---|---|---|---|---|---|
| Basic support | ? | 18 (18) | ? | ? | ? |
| Feature | Android | Chrome for Android | Firefox Mobile (Gecko) | IE Mobile | Opera Mobile | Safari Mobile |
|---|---|---|---|---|---|---|
| Basic support | ? | ? | 18.0 (18) | ? | ? | ? |
兼容性注意事项
Firefox火狐
- 在Gecko 42 (Firefox 42 / Thunderbird 42 / SeaMonkey 2.39)版本中,
ownKey的实施已经更新了,为了反映最终的ES5标准 (see bug 1049662):- 现在需要检查结果是不是数组以及数组元素类型是不是string或symbol.
- 枚举重复的自有的属性名称不再失败.