Dangers of Inheritance

Two common traps when working with prototypes:

Trap 1: Property Shadowing

Writing obj.prop = value ALWAYS writes to the object itself — NOT its prototype. The prototype property gets " shadowed " .

let animal = { eats: true };
let rabbit = Object.create(animal);

rabbit.eats = false; // Creates OWN property, does NOT change animal!

console.log(rabbit.eats); // false — reads own property
console.log(animal.eats); // true — prototype unchanged!

Trap 2: Mutating Shared Objects in Prototypes

If a prototype contains an array or object, mutating it (e.g., .push()) affects ALL inheritors!

let hamster = { stomach: [] }; // shared!
let speedy = Object.create(hamster);
let lazy = Object.create(hamster);

speedy.stomach.push('apple'); // mutates the SHARED prototype array!
console.log(lazy.stomach); // ['apple'] — lazy ate nothing!

Fix: Assign a new value: speedy.stomach = ['apple'].

Caution

Always assign new arrays/objects (obj.arr = [newVal]) rather than mutating shared ones.

Tip

Use Object.hasOwn(obj, prop) — the modern replacement for hasOwnProperty — to check if a property is own or inherited.