JavaScript(JS) object method - setPrototypeOf
The setPrototypeOf()
method is a built-in method of the JavaScript Object
constructor. It sets the prototype (i.e., the internal [[Prototype]]
property) of a specified object to another object or null
. This method is useful when you want to change the prototype of an object after it has been created.
Here's the syntax:
Object.setPrototypeOf(obj, prototype)
where obj
is the object whose prototype we want to set, and prototype
is the object to set as the new prototype of the object. If prototype
is null
, the object's prototype will be set to null
.
Here's an example that shows how to use the setPrototypeOf()
method:
const myObj = { prop1: "value1" }; const myProto = { prop2: "value2" }; console.log(Object.getPrototypeOf(myObj)); // {} console.log(myObj.prop2); // undefined Object.setPrototypeOf(myObj, myProto); console.log(Object.getPrototypeOf(myObj)); // { prop2: "value2" } console.log(myObj.prop2); // "value2"
In this example, we create an object myObj
with one property prop1
, and another object myProto
with one property prop2
. We use the Object.getPrototypeOf()
method to get the prototype of myObj
, which is an empty object {}
by default. We then try to access the prop2
property of myObj
, which is undefined
since it does not exist.
Next, we use the Object.setPrototypeOf()
method to set the prototype of myObj
to myProto
. We use the Object.getPrototypeOf()
method again to get the new prototype of myObj
, which is now the myProto
object containing the prop2
property. We can now access the prop2
property of myObj
and see that its value is "value2"
.
The setPrototypeOf()
method is useful when you want to change the prototype of an object after it has been created. However, changing an object's prototype can have unintended consequences and is generally not recommended. It is better to set the prototype of an object when it is created using the Object.create()
method or by using a class constructor.