handler.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

const monster = {
  eyeCount: 4,
};

const handler = {
  getOwnPropertyDescriptor(target, prop) {
    console.log(`called: ${prop}`);
    // Expected output: "called: eyeCount"

    return { configurable: true, enumerable: true, value: 5 };
  },
};

const proxy = new Proxy(monster, handler);

console.log(Object.getOwnPropertyDescriptor(proxy, "eyeCount").value);
// Expected output: 5

Syntax

js
new Proxy(target, {
  getOwnPropertyDescriptor(target, property) {
  }
})

Parameters

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

target

The target object.

property

A string or Symbol representing the property name.

Return value

The getOwnPropertyDescriptor() method must return an object or undefined, representing the property descriptor. Missing attributes are normalized in the same way as Object.defineProperty().

Description

undefined

Interceptions

This trap can intercept these operations:

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

Invariants

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

Examples

undefined

Trapping of 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

Specifications

See also