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, AliceObject.getPrototypeOf() Example:
console.log(Object.getPrototypeOf(obj) === proto); // trueUsing 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] }Read more
Stuck on this one? Talk to Sumit.
Keys: F focus mode · ← → previous / next topic · Esc leave focus