What is Object.setPrototypeOf() in JavaScript?

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.

Return value

The setPrototypeOf() method returns an object obj with prototype prototype.

Note: If obj is non-extensible, TypeError is thrown.

Browser compatibility

The setPrototypeOf() method is supported by the following browsers:

Code

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())

Explanation

  • An object shape is declared with property1() in line 1.
  • An object triangle is declared with property2() in line 6.
  • The prototype of 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.
Copyright ©2024 Educative, Inc. All rights reserved