Skip to content
Related Articles

Related Articles

Improve Article
JavaScript | handler.getPrototypeOf() Method
  • Last Updated : 27 Mar, 2020

The handler.getPrototypeOf() method in JavaScript is a trap for the internal method. This method returns the same value as Object.getPrototypeOf(target).

Syntax:

const p = new Proxy(obj, {
  getPrototypeOf(target) {
  ...
  }
}); 

Parameters:

  • target: The target object.

Return value: This method always returns an object if no object is returned it return a null.

Below examples illustrate the handler.getPrototypeOf() method in JavaScript:



Example 1:




<script>
const monster1 = {
  porp: 46
};
  
const monsterPrototype = {
  porp : 52
};
  
const handler = {
  getPrototypeOf(target) {
    return monsterPrototype;
  }
};
  
const proxy1 = new Proxy(monster1, handler);
console.log(Object.getPrototypeOf(proxy1) === monsterPrototype);
console.log(Object.getPrototypeOf(proxy1).porp);
  
  
var obj = {};  
var p = new Proxy(obj, {  
    getPrototypeOf(target) {  
        return Array.prototype;  
    }  
});  
console.log(  
    p instanceof Array    
);  
</script>

Output:

true
52
true

Example 2: Five ways to trigger this method of trap




<script>
const obj = {};
const p = new Proxy(obj, {
    getPrototypeOf(target) {
        return Array.prototype;
    }
});
document.writeln(Object.getPrototypeOf(p) === Array.prototype);
document.writeln("<br>");
document.writeln(Reflect.getPrototypeOf(p) === Array.prototype); 
document.writeln("<br>");
document.writeln(p.__proto__ === Array.prototype);
document.writeln("<br>");
document.writeln(Array.prototype.isPrototypeOf(p));              
document.writeln("<br>");
document.writeln(p instanceof Array );
</script>

Output:

true
true
true
true
true

Type of exceptions:

  1. TypeError: “target” is not an object or null
    Example 1:




    <script>
     const obj = {};
    const p = new Proxy(obj, {
        getPrototypeOf(target) {
            return 'Geeksforgeeks';
        }
    });
    console.log(Object.getPrototypeOf(p)); 
    </script>

    Output:

    Error: 'getPrototypeOf' on proxy: trap returned
    neither object nor null
  2. TypeError: expected same prototype value

    Example 2: TypeError: expected same prototype value




    <script>
     const obj = Object.preventExtensions({});
    const p = new Proxy(obj, {
        getPrototypeOf(target) {
            return {};
        }
    });
    console.log(Object.getPrototypeOf(p));
    </script>

    Output:

    Error: 'getPrototypeOf' on proxy: proxy target is non-extensible
    but the trap did not return its actual prototype

Supported Browsers: The browsers supported by handler.getPrototypeOf() method are listed below:

  • Google Chrome
  • Firefox
  • Opera
  • Safari
  • Edge



My Personal Notes arrow_drop_up
Recommended Articles
Page :