The handler.getPrototypeOf()
method is a trap for the [[GetPrototypeOf]]
internal method.
The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
Syntax
const p = new Proxy(obj, { getPrototypeOf(target) { ... } });
Parameters
The following parameter is passed to the getPrototypeOf()
method. this
is bound to the handler.
target
- The target object.
Return value
The getPrototypeOf()
method must return an object or null
.
Description
Interceptions
This trap can intercept these operations:
Object.getPrototypeOf()
Reflect.getPrototypeOf()
__proto__
Object.prototype.isPrototypeOf()
instanceof
Invariants
If the following invariants are violated, the proxy will throw a TypeError
:
getPrototypeOf()
method must return an object ornull
.- If
target
is not extensible,Object.getPrototypeOf(proxy)
method must return the same value asObject.getPrototypeOf(target)
.
Examples
Basic usage
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
Five ways to trigger the getPrototypeOf trap
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 );
Two kinds of exceptions
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
Specifications
Specification |
---|
ECMAScript (ECMA-262) The definition of '[[GetPrototypeOf]]' in that specification. |
Browser compatibility
The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request.
Desktop | Mobile | Server | |||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
getPrototypeOf | Chrome Full support 49 | Edge Full support 79 | Firefox Full support 49 | IE No support No | Opera Full support 36 | Safari No support No | WebView Android Full support 49 | Chrome Android Full support 49 | Firefox Android Full support 49 | Opera Android Full support 36 | Safari iOS No support No | Samsung Internet Android Full support 5.0 | nodejs Full support 6.0.0 |
Legend
- Full support
- Full support
- No support
- No support