handler.getOwnPropertyDescriptor()

handler.getOwnPropertyDescriptor() 方法是对 [[GetOwnProperty]] 对象内部方法 的陷阱,被 Object.getOwnPropertyDescriptor() 等操作使用。

¥The handler.getOwnPropertyDescriptor() method is a trap for the [[GetOwnProperty]] object internal method, which is used by operations such as Object.getOwnPropertyDescriptor().

Try it

语法

¥Syntax

js
new Proxy(target, {
  getOwnPropertyDescriptor(target, prop) {
  }
});

参数

¥Parameters

以下参数传递给 getOwnPropertyDescriptor() 方法。this 绑定到处理程序。

¥The following parameters are passed to the getOwnPropertyDescriptor() method. this is bound to the handler.

target

目标对象。

prop

应检索其描述的属性的名称。

返回值

¥Return value

getOwnPropertyDescriptor() 方法必须返回一个对象或 undefined

¥The getOwnPropertyDescriptor() method must return an object or undefined.

描述

¥Description

拦截

¥Interceptions

该陷阱可以拦截以下操作:

¥This trap can intercept these operations:

或调用 [[GetOwnProperty]] 内部方法 的任何其他操作。

¥Or any other operation that invokes the [[GetOwnProperty]] internal method.

不变量

¥Invariants

如果违反以下不变量,则陷阱在调用时会抛出 TypeError

¥If the following invariants are violated, the trap throws a TypeError when invoked.

  • getOwnPropertyDescriptor() 必须返回一个对象或 undefined
  • 如果属性作为目标对象的不可配置自有属性存在,则不能将其报告为不存在。
  • 如果属性作为目标对象自己的属性存在并且目标对象不可扩展,则不能将其报告为不存在。
  • 如果属性不作为目标对象自己的属性存在并且目标对象不可扩展,则不能将其报告为存在。
  • 如果某个属性不作为目标对象的自有属性存在,或者作为目标对象的可配置自有属性存在,则该属性不能报告为不可配置。
  • Object.getOwnPropertyDescriptor(target) 的结果可以使用 Object.defineProperty() 应用到目标对象,并且不会抛出异常。

示例

¥Examples

getOwnPropertyDescriptor 的捕获

¥Trapping of getOwnPropertyDescriptor

以下代码捕获 Object.getOwnPropertyDescriptor()

¥The following code traps Object.getOwnPropertyDescriptor().

js
const p = new Proxy(
  { a: 20 },
  {
    getOwnPropertyDescriptor(target, prop) {
      console.log(`called: ${prop}`);
      return { configurable: true, enumerable: true, value: 10 };
    },
  },
);

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

以下代码违反了不变量。

¥The following code violates an invariant.

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

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

规范

Specification
ECMAScript Language Specification
# sec-proxy-object-internal-methods-and-internal-slots-getownproperty-p

¥Specifications

浏览器兼容性

BCD tables only load in the browser

¥Browser compatibility

也可以看看