JavaScript Object setPrototypeOf() Method
Last Updated :
12 Jul, 2024
Improve
The Object.setPrototypeOf() method in JavaScript is a standard built-in object thatthat will
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 accepts two parameters as mentioned above and described below:
- obj: This parameter is the object that will have its prototype set.
- Prototype: This parameter is the object's new prototype. It can be an object or a null object.
Return value:
- This method returns the specified object.
Example 1: In this example, we will set a prototype of an object using the Object.setPrototypeOf() Method in JavaScript.
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());
Output:
"Geeksforgeeks"
"JavaScript "
"Object.isExtensible()"
Example 2: In this example, we will set a prototype of an object using the Object.setPrototypeOf() Method in JavaScript.
let 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);
let result = new geeks2('GeeksforGeeks');
result.prop1();
result.prop2();
Output:
"GeeksforGeeks is Best platform"
"GeeksforGeeks provide jobs opportunity"
We have a complete list of Javascript Object methods, to check those please go through this JavaScript Object Complete Reference article.
Supported Browsers:
The browsers supported by Object.setPrototypeOf() method are listed below:
- Google Chrome
- Edge
- Firefox
- Opera
- Safari