Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

javascript

What is Object.setPrototypeOf() in JavaScript?

Syed Muhammad Ali Mustafa

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

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.

RELATED TAGS

javascript

CONTRIBUTOR

Syed Muhammad Ali Mustafa
Copyright ©2022 Educative, Inc. All rights reserved

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring