After this lesson, you will be able to: Understand the prototype chain, how inheritance works without classes, and what ES6 classes actually compile to.
ES6 classes are syntactic sugar over prototypes. Understanding the underlying model is what makes 'this' debuggable.
Property lookup walks the prototype chain.
const animal = { speak() { return "..."; } };const dog = Object.create(animal); // dog's __proto__ = animaldog.bark = function () { return "Woof"; };dog.bark(); // "Woof", found on dogdog.speak(); // "...", found via dog.__proto__dog.unknown; // undefined, chain ends at Object.prototype// Modern: Object.getPrototypeOf(dog) === animal
Same chain, friendlier syntax.
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:// d.__proto__ === Dog.prototype// Dog.prototype.__proto__ === Animal.prototype// Animal.prototype.__proto__ === Object.prototype
In methods, `this` is whatever called the method (the object before the dot). Detached: `const fn = obj.method; fn();` → `this` is undefined (strict) or global. Arrow functions DON'T have their own `this`; they inherit from enclosing scope. Use arrow functions for callbacks; regular methods for class methods.
The most-asked JS this question.
class Counter {constructor() { this.count = 0; }increment() { this.count++; }}const c = new Counter();setTimeout(c.increment, 1000); // TypeError: Cannot set property 'count' of undefined// `c.increment` is a bare function reference; `this` is lost.// Fix 1: bindsetTimeout(c.increment.bind(c), 1000);// Fix 2: arrow wrappersetTimeout(() => c.increment(), 1000);// Fix 3: class field arrow (auto-bound)class Counter {count = 0;increment = () => { this.count++; };}
Modifying built-in prototypes (Array.prototype.x = ...). Breaks everyone else's code. Confusing `instanceof` with prototype-chain inheritance. Detached methods losing `this`. Using arrow functions for class methods that should be on the prototype (memory hit: one copy per instance).
Pick the cleanest answer.
Sign in and purchase access to unlock this lesson.