Skip to content
Related Articles

Related Articles

Improve Article

JavaScript | handler.setPrototypeOf() Method

  • Last Updated : 29 Sep, 2021
Geek Week

The handler.setPrototypeOf() method in JavaScript is a trap for Object.setPrototypeOf() method and it returns a Boolean value.
Syntax: 
 

const p = new Proxy(target, {
  setPrototypeOf: function(target, prototype) {
  }
});

Parameters: This method accept two parameters as mentioned above and described below: 
 

  • target: This parameter is the target object.
  • prototype: This parameter is the object’s new prototype or null.

Return value: This method returns a boolean value. It returns true if the [[Prototype]] was successfully changed.
Below examples illustrate the handler.setPrototypeOf() method in JavaScript:
Example 1: 
 

javascript




<script>
const handler1 = {
  setPrototypeOf(gfg, gfgProto) {
    gfg.geneticallyModified = true;
    return false;
  }
};
 
const gfgProto = {};
const gfg = {
  geneticallyModified : false
};
 
const proxy1 = new Proxy(gfg, handler1);
console.log(Reflect.setPrototypeOf(proxy1, gfgProto));
console.log(gfg.geneticallyModified);
 
var soo={ 
  foo:1 
var proxy = new Proxy(soo, { 
  setPrototypeOf(target, newProto) { 
  
}); 
console.log('a' in proxy);
</script>

Output: 
 

false
true
false

Example 2: 
 



javascript




<script>
const handlerThrows = {
    setPrototypeOf(target, newProto) {
        throw new Error('custom error');
    }
};
 
const newProto = {}, target = {};
 
const p2 = new Proxy(target, handlerThrows);
document.writeln(Object.setPrototypeOf(p2, newProto)); 
document.writeln(Reflect.setPrototypeOf(p2, newProto));
</script>

Output: 
 

Error: custom error

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

  • Google Chrome 49 and above
  • Edge 12 and above
  • Firefox 49 and above
  • Opera 36 and above
  • Safari 10 and above

 

Hey geek! The constant emerging technologies in the world of web development always keeps the excitement for this subject through the roof. But before you tackle the big projects, we suggest you start by learning the basics. Kickstart your web development journey by learning JS concepts with our JavaScript Course. Now at it’s lowest price ever!




My Personal Notes arrow_drop_up
Recommended Articles
Page :