Skip to content
Related Articles

Related Articles

Improve Article

JavaScript | Reflect.setPrototypeOf() Method

  • Last Updated : 30 Sep, 2021
Geek Week

The Reflect.setPrototypeOf() method in JavaScript is used to set the prototype of a specified object to another object or to Null. This method returns the boolean value for the operation that are successful.
Syntax: 
 

Reflect.setPrototypeOf(obj, prototype)

Parameters: 
 

  • Obj: This parameter holds the target object and it is used to set the prototype.
  • Prototype: This parameter holds the object’s new prototype. It can be any object or simply a null.

Return value: This method always returns a Boolean value which indicates whether setting the prototype was successfully done or not.
Exceptions:A TypeError is exception given as the result, when the target is not object.
Below examples illustrate the Reflect.setPrototypeOf() method in JavaScript:
Example 1: 
 

javascript




const object1 = {};
 
console.log(Reflect.setPrototypeOf(object1, Object.prototype));
console.log(Reflect.setPrototypeOf(object1, null));
 
const object2 = {};
console.log(Reflect.setPrototypeOf(Object.freeze(object2), null));
 
let object3 = { 
  gfg() { 
    return 'value'
  
let obj = { 
  geeks() { 
    return 'answer'
  
Object.setPrototypeOf(obj, object3); 
console.dir(obj);  
console.log(obj.geeks());   
console.log(obj.gfg()); 

Output: 
 

true
true
false
"answer"
"value"

Example 2: 
 



javascript




console.log(Reflect.setPrototypeOf({}, Object.prototype) );
  
// It can change an object's [[Prototype]] to null.
console.log(Reflect.setPrototypeOf({}, null));
  
// Returns false if target is not extensible.
console.log(Reflect.setPrototypeOf(Object.freeze({}), null)); 
  
// Returns false if it cause a prototype chain cycle.
let target = {}
let proto = Object.create(target)
console.log(Reflect.setPrototypeOf(target, proto) ); 
  
var object3 = { 
   gfg() { 
     console.log(this.name + ' have fun.'); 
   
}; 
class objt { 
   constructor(name) { 
   this.name = name; 
  
Reflect.setPrototypeOf(objt.prototype, object3); 
 
// If you do not do this you will get
// a TypeError when you invoke speak 
var val = new objt('Geeks'); 
val.gfg();

Output: 
 

true
true
false
false
"Geeks have fun."

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

  • Google Chrome 49 and above
  • Edge 12 and above
  • Firefox 42 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 :