UNB/ CS/ David Bremner/ teaching/ cs2613/ books/ mdn/ Reference/ Global Objects/ Proxy/ Proxy/ handler.get()

The handler.get() method is a trap for the <span class="selflink">Get</span> object internal method, which is used by operations such as property accessors.

Syntax

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

Parameters

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

Return value

The get() method can return any value.

Description

Interceptions

This trap can intercept these operations:

Or any other operation that invokes the <span class="selflink">Get</span> internal method.

Invariants

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

Examples

Trap for getting a property value

The following code traps getting a property value.

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.

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

Specifications

Browser compatibility

See also