Changing an Object's Prototype
You'll learn: How to change an object's prototype after creation using Object.setPrototypeOf() and why you should avoid it.
The Basics
While prototypes are usually set when an object is created, JavaScript provides Object.setPrototypeOf() to change an object's prototype after the fact:
const animal = {
eats: true
};
const rabbit = {
jumps: true
};
console.log(rabbit.eats); // undefined
Object.setPrototypeOf(rabbit, animal);
console.log(rabbit.eats); // true (now inherited from animal)
console.log(Object.getPrototypeOf(rabbit) === animal); // true
Why This is Discouraged
Performance Impact: Modern JavaScript engines optimize property access based on an object's prototype chain. When you change a prototype after creation, you break these optimizations, making property lookups significantly slower—not just for that object, but potentially for all objects that shared similar structures.
Think of it like rearranging a library's organization system after patrons have memorized where everything is. Everyone has to relearn, and future searches are slower.
When It Happens
You might see Object.setPrototypeOf() in legacy code or specific metaprogramming scenarios, but it's almost always better to set the prototype at creation time (which we'll learn about in future lessons).
// Changing prototype = slow
const obj = {};
Object.setPrototypeOf(obj, somePrototype); // ⚠️ Performance hit
// Better approach (for later): set prototype at creation
Key Takeaway: Object.setPrototypeOf() can change an object's prototype after creation, but it causes severe performance penalties and should be avoided in production code.