The Object.setPrototypeOf() method sets the prototype of the specified object to another object or null.
Example
setPrototypeOf() Syntax
The syntax of the setPrototypeOf() method is:
Object.setPrototypeOf(obj, prototype)
The setPrototypeOf() method, being a static method, is called using the Object class name.
setPrototypeOf() Parameters
The setPrototypeOf() method takes in:
- obj - the object whose prototype we want to set.
- prototype - the object's new prototype (an object or null).
setPrototypeOf() Return Value
The setPrototypeOf() method returns the object whose prototype we want to set i.e. obj.
Note: Changing the [[Prototype]] of an object is currently a very slow operation in every browser and JavaScript engine.
Example 1: JavaScript Object.setPrototypeOf()
In the above example, the Animal object is set as the prototype of the dog1 object using the Object.setPrototypeOf() method.
Hence, we are able to access the makeSound() method of Animal using the dog1 object, even though it is not defined inside the Dog() constructor function.
Example 2: Using setPrototypeOf() With Class
In the above example, the setPrototypeOf() method is used to set the prototype of objects of the Dog class to the Animal object.
As a result, all the instances of the Dog class (dog1 in our case) can inherit and call the makeSound() method from the Animal object.
Recommended Reading: