handler.getOwnPropertyDescriptor() 方法是 Object.getOwnPropertyDescriptor()  的陷阱。

语法

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

参数

下列参数会被传入 getOwnPropertyDescriptor 方法中。这是绑定到处理程序。 

target
目标对象。
prop
返回属性名称的描述。

返回值

getOwnPropertyDescriptor 方法必须返回一个 object 或 undefined。

描述

handler.getOwnPropertyDescriptor() 方法是 Object.getOwnPropertyDescriptor() 的陷阱。

拦截

这个陷阱可以拦截这些操作:

不变量

如果下列不变量被违反,代理将抛出一个 TypeError

示例

以下是 Object.getOwnPropertyDescriptor() 的代码陷阱:

var p = new Proxy({ a: 20}, {
  getOwnPropertyDescriptor: function(target, prop) {
    console.log('called: ' + prop);
    return { configurable: true, enumerable: true, value: 10 };
  }
});

console.log(Object.getOwnPropertyDescriptor(p, 'a').value); // "called: a"
                                                            // 10

以下代码则违反了不变量。

var obj = { a: 10 };
Object.preventExtensions(obj);
var p = new Proxy(obj, {
  getOwnPropertyDescriptor: function(target, prop) {
    return undefined;
  }
});

Object.getOwnPropertyDescriptor(p, 'a'); // TypeError is thrown

规范

Specification Status Comment
ECMAScript 2015 (6th Edition, ECMA-262)
[[GetOwnProperty]]
Standard Initial definition.
ECMAScript Latest Draft (ECMA-262)
[[GetOwnProperty]]
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) ? ? ?

相关链接