JavaScript Handler getPrototypeOf() Method



In JavaScript, Proxy objects can utilize handler.getPrototypeOf() to intercept calls to Object.getPrototypeOf(). It allows customization of prototype retrieval behavior. The handler getPrototypeOf() is invoked when the prototype of an object is accessed. This enables dynamic control over prototype access, facilitating features like virtualization and encapsulation. The default prototype lookup is carried out if the handler doesn't define getPrototypeOf(). This method is essential for including functionalities like inheritance and object composition.

Syntax

Following is the syntax of JavaScript handler.getPrototypeOf() method −

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

Parameters

  • target − It holds the target object.

Return value

This method returns an object or null if no no object is returned.

Example 1

Let's look at the following example, where we are going to use the handler.getPrototypeOf() to retrieve the prototype of the proxy object.

<html>
<style>
body {
   font-family: verdana;
   color: #DE3163;
}
</style>
<body>
<script>
const x = {};
const y = {
   getPrototypeOf(target) {
      return Object.getPrototypeOf(target);
   }
};
const z = new Proxy(x, y);
document.write(y.getPrototypeOf(z) === Object.getPrototypeOf(z));
</script>
</body>
</html>

Output

If we execute the above program, it will displays a text on the webpage.

Example 2

Consider another scenario where we are going to prevent the access to the prototype of the target object.

<html>
<style>
body {
   font-family: verdana;
   color: #DE3163;
}
</style>
<body>
<script>
const x = {};
const y = {
   getPrototypeOf: function(target) {
      return null;
   }
};
const z = new Proxy(x, y);
document.write(Object.getPrototypeOf(z));
</script>
</body>
</html>

Output

On executing the above script, it will displays null text on the webpage.

Example 3

In the following example, we are going to use the handler.getPrototypeOf() to dynamically adjusts the prototype of the proxy object to Array.prototype.

<html>
<style>
body {
   font-family: verdana;
   color: #DE3163;
}
</style>
<body>
<script>
const x = {};
const y = {
   getPrototypeOf(target) {
      return Array.prototype;
   }
};
const z = new Proxy(x, y);
document.write(y.getPrototypeOf(z) === Array.prototype);
</script>
</body>
</html>

When we execute the above code, it will generate an output consisting of the text displayed on the webpage.

Advertisements