handler.ownKeys() 方法用于拦截 Reflect.ownKeys().

语法

var p = new Proxy(target, {
  ownKeys: function(target) {
  }
});

参数

下面的参数被传递给ownKeys。this被绑定在handler上。

target
目标对象.

返回值

ownKeys 方法必须返回一个可枚举对象.

描述

handler.ownKeys() 方法用于拦截 Reflect.ownKeys().

拦截

该拦截器可以拦截以下操作::

约定

如果违反了下面的约定,proxy将抛出错误 TypeError:

示例

下面的代码拦截 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火狐

另见