This page was translated from English by the community. Learn more and join the MDN Web Docs community.

View in English Always switch to English

handler.getPrototypeOf()

Baseline Widely available

This feature is well established and works across many devices and browser versions. It’s been available across browsers since ⁨2020년 1월⁩.

handler.getPrototypeOf() 메서드는 [[GetPrototypeOf]] 내부 메서드에 대한 트랩입니다.

시도해 보기

const monster1 = {
  eyeCount: 4,
};

const monsterPrototype = {
  eyeCount: 2,
};

const handler = {
  getPrototypeOf(target) {
    return monsterPrototype;
  },
};

const proxy1 = new Proxy(monster1, handler);

console.log(Object.getPrototypeOf(proxy1) === monsterPrototype);
// Expected output: true

console.log(Object.getPrototypeOf(proxy1).eyeCount);
// Expected output: 2

구문

js
new Proxy(obj, {
  getPrototypeOf(target) {
    // …
  },
});

매개변수

다음 매개변수는 getPrototypeOf() 메서드에 전달됩니다. this는 처리기에 바인딩됩니다.

target

대상 객체

반환 값

getPrototypeOf() 메서드는 객체 또는 null을 반환합니다.

설명

가로채기

이 트랩은 다음 작업을 가로챌 수 있습니다.

불변 조건

다음 불변 조건이 위반되면 프록시에서 TypeError가 발생합니다.

  • getPrototypeOf() 메서드는 반드시 객체나 null을 반환해야 합니다.
  • target을 확장할 수 없는 경우, Object.getPrototypeOf(proxy) 메서드는 Object.getPrototypeOf(target)과 동일한 값을 반환해야 합니다.

예제들

기본 사용법

js
const obj = {};
const proto = {};
const handler = {
  getPrototypeOf(target) {
    console.log(target === obj); // true
    console.log(this === handler); // true
    return proto;
  },
};

const p = new Proxy(obj, handler);
console.log(Object.getPrototypeOf(p) === proto); // true

getPrototypeOf 트랩을 싱핼 시키는 5가지 방법

js
const obj = {};
const p = new Proxy(obj, {
  getPrototypeOf(target) {
    return Array.prototype;
  },
});
console.log(
  Object.getPrototypeOf(p) === Array.prototype, // true
  Reflect.getPrototypeOf(p) === Array.prototype, // true
  p.__proto__ === Array.prototype, // true
  Array.prototype.isPrototypeOf(p), // true
  p instanceof Array, // true
);

두 가지 예외

js
const obj = {};
const p = new Proxy(obj, {
  getPrototypeOf(target) {
    return "foo";
  },
});
Object.getPrototypeOf(p); // TypeError: "foo" is not an object or null

const obj = Object.preventExtensions({});
const p = new Proxy(obj, {
  getPrototypeOf(target) {
    return {};
  },
});
Object.getPrototypeOf(p); // TypeError: expected same prototype value

명세서

Specification
ECMAScript® 2026 Language Specification
# sec-proxy-object-internal-methods-and-internal-slots-getprototypeof

브라우저 호환성

같이 보기