JavaScript | Object.setPrototypeOf() Method

The Object.setPrototypeOf() method in JavaScript is standard built-in objects which sets the prototype (i.e., the internal [[Prototype]] property) of a specified object to another object or null.

Syntax:

Object.setPrototypeOf(obj, prototype)

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

  • obj:This parameter is the object which is going to have its prototype set.
  • Prototype:This parameter is the object’s new prototype. It can be an object or null object.

Return value: This method returns the specified object.

Below examples illustrate the Object.setPrototypeOf() Method in JavaScript:



Example 1:

filter_none

edit
close

play_arrow

link
brightness_4
code

let geek1 = {  
  prop1() {  
    return 'Object.isExtensible()';  
  },
  prop2() {  
    return 'JavaScript ';  
  
}  
let geek2  = {  
  prop3() {  
    return 'Geeksforgeeks';  
  }  
}  
  
Object.setPrototypeOf(geek2, geek1);  
    
console.dir(geek2); 
console.log(geek2.prop3()); 
console.log(geek2.prop2()); 
console.log(geek2.prop1()); 

chevron_right


Output:

"Geeksforgeeks"
"JavaScript "
"Object.isExtensible()"

Example 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

var geeks1 = {  
   prop1() {  
     console.log(this.name + ' is Best platform');  
   },
   prop2() {  
     console.log(this.name + ' provide jobs opportunity');  
   }
};  
    
class geeks2 {  
   constructor(name) {  
   this.name = name;  
  }  
}  
    
Object.setPrototypeOf(geeks2.prototype, geeks1);   
var result = new geeks2('GeeksforGeeks');  
result.prop1();
result.prop2();

chevron_right


Output:

"GeeksforGeeks is Best platform"
"GeeksforGeeks provide jobs opportunity"

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

  • Google Chrome
  • Firefox
  • IE
  • Opera
  • Safari
  • Edge

full-stack-img




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.