CodeMasteryLab
Section 7

Prototypes & Prototype Chain

JavaScript's object-oriented foundation — prototypal inheritance, the prototype chain, and how ES6 classes are just syntactic sugar.

Prototypes & Prototype Chain

JavaScript uses prototypal inheritance, not classical inheritance. Understanding this is crucial for senior-level interviews.

Every Object Has a Prototype

const obj = { name: 'Alice' };
console.log(obj.__proto__ === Object.prototype); // true
console.log(Object.prototype.__proto__); // null (end of chain)

Prototype Chain Lookup

When you access a property, JS looks in the object itself first, then up the chain:

function Animal(name) {
  this.name = name;
}
Animal.prototype.speak = function() {
  return this.name + ' makes a sound.';
};

const dog = new Animal('Rex');
console.log(dog.speak());    // 'Rex makes a sound.' (found on prototype)
console.log(dog.hasOwnProperty('name')); // true (own property)
console.log(dog.hasOwnProperty('speak')); // false (on prototype)

ES6 Classes = Syntactic Sugar

class Animal {
  constructor(name) { this.name = name; }
  speak() { return this.name + ' makes a sound.'; }
}

class Dog extends Animal {
  speak() { return this.name + ' barks.'; }
}

const d = new Dog('Rex');
d.speak(); // 'Rex barks.'

Under the hood, this uses the same prototype chain.