handler.get()

handler.get() 方法是对 [[Get]] 对象内部方法 的陷阱,被 属性访问器 等操作使用。

¥The handler.get() method is a trap for the [[Get]] object internal method, which is used by operations such as property accessors.

Try it

语法

¥Syntax

js
new Proxy(target, {
  get(target, property, receiver) {
  }
})

参数

¥Parameters

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

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

target

目标对象。

property

表示属性名称的字符串或 Symbol

receiver

getter 的 this 值;见 Reflect.get()。这通常是代理本身或从代理继承的对象。

返回值

¥Return value

get() 方法可以返回任何值,表示属性值。

¥The get() method can return any value, representing the property value.

描述

¥Description

拦截

¥Interceptions

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

¥This trap can intercept these operations:

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

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

不变量

¥Invariants

如果处理程序定义违反以下不变量之一,则代理的 [[Get]] 内部方法将抛出 TypeError

¥The proxy's [[Get]] internal method throws a TypeError if the handler definition violates one of the following invariants:

  • 如果目标对象属性是不可写、不可配置的自有数据属性,则为属性报告的值必须与相应的目标对象属性的值相同。也就是说,如果 Reflect.getOwnPropertyDescriptor()target 上的属性返回 configurable: false, writable: false,则陷阱必须返回与 target 的属性描述符中的 value 属性相同的值。
  • 如果相应的目标对象属性是具有未定义 getter 的不可配置自有访问器属性,则为属性报告的值必须是 undefined。也就是说,如果 Reflect.getOwnPropertyDescriptor()target 上的属性返回 configurable: false, get: undefined,则陷阱必须返回 undefined

示例

¥Examples

获取属性价值的陷阱

¥Trap for getting a property value

以下代码捕获获取属性值的陷阱。

¥The following code traps getting a property value.

js
const p = new Proxy(
  {},
  {
    get(target, property, receiver) {
      console.log(`called: ${property}`);
      return 10;
    },
  },
);

console.log(p.a);
// "called: a"
// 10

以下代码违反了不变量。

¥The following code violates an invariant.

js
const obj = {};
Object.defineProperty(obj, "a", {
  configurable: false,
  enumerable: false,
  value: 10,
  writable: false,
});

const p = new Proxy(obj, {
  get(target, property) {
    return 20;
  },
});

p.a; // TypeError is thrown

规范

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

¥Specifications

浏览器兼容性

BCD tables only load in the browser

¥Browser compatibility

也可以看看