handler.getPrototypeOf()
The handler.getPrototypeOf()
method is a trap for the [[GetPrototypeOf]]
internal method.
Syntax
JavaScript
Copy Code
var 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
JavaScript
Copy Code
var obj = {}; var proto = {}; var handler = { getPrototypeOf(target) { console.log(target === obj); // true console.log(this === handler); // true return proto; } }; var p = new Proxy(obj, handler); console.log(Object.getPrototypeOf(p) === proto); // true
Five ways to trigger the getPrototypeOf trap
JavaScript
Copy Code
var obj = {}; var 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
JavaScript
Copy Code
var obj = {}; var p = new Proxy(obj, { getPrototypeOf(target) { return "foo"; } }); Object.getPrototypeOf(p); // TypeError: "foo" is not an object or null var obj = Object.preventExtensions({}); var p = new Proxy(obj, { getPrototypeOf(target) { return {}; } }); Object.getPrototypeOf(p); // TypeError: expected same prototype value
Specifications
Specification | Status | Comment |
---|---|---|
ECMAScript 2015 (6th Edition, ECMA-262) The definition of '[[GetPrototypeOf]]' in that specification. |
Standard | Initial definition. |
ECMAScript 2017 Draft (ECMA-262) The definition of '[[GetPrototypeOf]]' in that specification. |
Draft |
Browser compatibility
Feature | Chrome | Firefox (Gecko) | Internet Explorer | Opera | Safari |
---|---|---|---|---|---|
Basic support | No support | 49 (49) | No support | No support | No support |
Feature | Android | Chrome for Android | Firefox Mobile (Gecko) | IE Mobile | Opera Mobile | Safari Mobile |
---|---|---|---|---|---|---|
Basic support | No support | No support | 49.0 (49) | No support | No support | No support |
See also
License
© 2016 Mozilla Contributors
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
https://developer.mozilla.org/en-us/docs/web/javascript/reference/global_objects/proxy/handler/getprototypeof