JavaScript Object setPrototypeOf() Method
Last Updated :
29 May, 2023
The Object.setPrototypeOf() method in JavaScript is a standard built-in object 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 accepts 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 a null object.
Return value: This method returns the specified object.
The below examples illustrate the Object.setPrototypeOf() Method in JavaScript:
Example 1: In this example, we will set a prototype of an object using the Object.setPrototypeOf() Method in JavaScript.
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.
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 34 and above
- Edge 12 and above
- Firefox 31 and above
- Opera 21 and above
- Safari 9 and above
Share your thoughts in the comments
Please Login to comment...