• JavaScript Video Tutorials

JavaScript Handler setPrototypeOf() Method



The handler.setPrototypeOf() method in JavaScript lets you set the prototype of a specified object to another object to another object. This method allows you to modify an object's prototype, effectively altering its inheritance chain. You can use this to dynamically change how objects behave within your code. However, it's important to use this method with caution as it can lead to unexpected behavior if not used properly. This method is also a part of the Proxy object handler, which lets you modify the behavior of Proxy objects by providing traps for them.

Syntax

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

new Proxy(target, {
   setPrototypeOf(target, prototype) {}
});

Parameters

  • target − It holds the target object.
  • prototype − It is the object new prototype or null.

Return value

This method returns a Boolean Value ana return true if the prototype was successfully changed.

Example 1

Let's look at the following example, where we are going to change prototype of an object.

<html>
<style>
body {
   font-family: verdana;
   color: #DE3163;
}
</style>
<body>
<script>
const x = {};
const y = {
   a: 10
};
const z = {
   setPrototypeOf(target, prototype) {
      return Reflect.setPrototypeOf(target, prototype);
   }
};
const b = new Proxy(x, z);
z.setPrototypeOf(b, y);
document.write(b.a);
</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 prototype changes.

<html>
<style>
body {
   font-family: verdana;
   color: #DE3163;
}
</style>
<body>
<script>
const x = {};
const y = {
   a: 10
};
const z = {
   setPrototypeOf(target, prototype) {
      console.error("Prototype setting is not allowed");
      return false;
   }
};
const b = new Proxy(x, z);
z.setPrototypeOf(b, y);
document.write(b.a);
</script>
</body>
</html>

Output

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

Example 3

In the following example, we are going to log the prototype changes whenever the object is changed.

<html>
<style>
body {
   font-family: verdana;
   color: #DE3163;
}
</style>
<body>
<script>
const a = {};
const b = {
   setPrototypeOf(target, proto) {
      document.write("Prototype changed to: " + JSON.stringify(d));
      return Reflect.setPrototypeOf(target, proto);
   }
};
const c = new Proxy(a, b);
const d = {
   x: 'WELCOME'
};
Object.setPrototypeOf(c, d);
</script>
</body>
</html>

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

Advertisements