The Object.setPrototypeOf() method sets the prototype of one object to another or null. The setPrototypeOf() method is declared as follows:
Object.setPrototypeOf(obj, prototype)
obj: The object whose prototype is set.prototype: The prototype that is set of obj.The setPrototypeOf() method returns an object obj with prototype prototype.
Note: If
objis non-extensible,TypeErroris thrown.
The setPrototypeOf() method is supported by the following browsers:
Consider the code snippet below, which demonstrates the use of the setPrototypeOf() method:
var shape = {property1(){return 'I am a shape'}}var triangle = {property2(){return 'I am a triangle'}}Object.setPrototypeOf(triangle, shape)console.log("triangle says: ", triangle.property1())console.log("triangle says: ", triangle.property2())
shape is declared with property1() in line 1.triangle is declared with property2() in line 6.shape is set to prototype of triangle using the setPrototypeOf() method in line 12.property1() is called from triangle in line 14, which was the prototype of shape.Free Resources