Skip to main content
TOPIC 6 OF 9 · 2 MIN READ

setPrototypeOf() and getPrototypeOf()

`Object.setPrototypeOf()` sets the prototype of an object, while `Object.getPrototypeOf()` retrieves the prototype of an object.

Key concepts

Object.setPrototypeOf()

Sets the prototype of an object.

Object.getPrototypeOf()

Retrieves the prototype of an object.

Examples

Object.setPrototypeOf() Example:

const proto = { greet: function () { console.log(`Hello, ${this.name}`); } };
const obj = { name: 'Alice' };

Object.setPrototypeOf(obj, proto);
obj.greet(); // Hello, Alice

Object.getPrototypeOf() Example:

console.log(Object.getPrototypeOf(obj) === proto); // true

Using setPrototypeOf() for Prototype Chain:

const proto = { walk: function () { console.log('Walking...'); } };
const obj = { name: 'Dog' };

Object.setPrototypeOf(obj, proto);

obj.walk(); // Walking...

Retrieving Prototype:

console.log(Object.getPrototypeOf(obj)); // { walk: [Function: walk] }

Stuck on this one? Talk to Sumit.

Keys: F focus mode · ← → previous / next topic · Esc leave focus