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

代理或继承自代理的对象。

返回值

¥Return value

get() 方法可以返回任何值。

¥The get() method can return any value.

描述

¥Description

拦截

¥Interceptions

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

¥This trap can intercept these operations:

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

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

不变量

¥Invariants

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

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

  • 如果目标对象属性是不可写、不可配置的自有数据属性,则为属性报告的值必须与相应目标对象属性的值相同。
  • 如果相应的目标对象属性是不可配置的自有访问器属性,并且具有 undefined 作为其 [[Get]] 属性,则为属性报告的值必须是未定义的。

示例

¥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

也可以看看