Object.getPrototypeOf and Object.setPrototypeOf in JS

JavaScript relies on prototype-based inheritance, where objects inherit properties and methods from other objects via an internal link known as [[Prototype]]. This article explains how Object.getPrototypeOf() and Object.setPrototypeOf() interact with this mechanism. You will learn their syntax, core behaviors, return values, edge cases, and the critical performance implications associated with mutating an object’s prototype at runtime.


Object.getPrototypeOf()

Object.getPrototypeOf() returns the prototype (the value of the internal [[Prototype]] property) of the specified object.

Syntax

Object.getPrototypeOf(obj)

Behavior and Return Value

Example

const parent = { greeting: "Hello" };
const child = Object.create(parent);

console.log(Object.getPrototypeOf(child) === parent); // true

// Coercion of primitives
console.log(Object.getPrototypeOf("text") === String.prototype); // true

Object.setPrototypeOf()

Object.setPrototypeOf() sets the prototype (i.e., the internal [[Prototype]] property) of a specified object to another object or null.

Syntax

Object.setPrototypeOf(obj, prototype)

Behavior and Return Value

Example

const animal = {
  speak() {
    return `${this.name} makes a sound.`;
  }
};

const dog = { name: "Rex" };

// Assign prototype
Object.setPrototypeOf(dog, animal);

console.log(dog.speak()); // "Rex makes a sound."
console.log(Object.getPrototypeOf(dog) === animal); // true

Performance Considerations

While Object.getPrototypeOf() is a fast, standard read operation, Object.setPrototypeOf() is considered a performance anti-pattern in modern JavaScript engines:

// Preferred approach instead of setPrototypeOf
const dog = Object.create(animal);
dog.name = "Rex";