MediumConcept

What is prototypal inheritance in JavaScript?

Technology:
JavaScript
Experience:
Mid-level,
Senior

Quick answer

In JavaScript every object has an internal link to another object called its prototype, and property lookups walk up this prototype chain until the property is found or the chain ends.

Detailed explanation

When you read obj.name, the engine checks obj first, then obj's prototype, then that object's prototype, and so on until it reaches null. Methods shared by all instances live on the prototype instead of being copied onto each object, which saves memory.

The class keyword is syntax over this mechanism. class B extends A sets up B.prototype to inherit from A.prototype. You can create an object with a chosen prototype using Object.create(proto), and inspect it with Object.getPrototypeOf(obj).

Example

javascript
const animal = { speak() { return this.name + " makes a sound"; } };
const dog = Object.create(animal);
dog.name = "Rex";
dog.speak();                              // "Rex makes a sound"
Object.getPrototypeOf(dog) === animal;    // true

class Cat {
  constructor(name) { this.name = name; }
  speak() { return this.name + " meows"; }   // lives on Cat.prototype
}

Key points

  • Lookups follow the prototype chain
  • class is syntactic sugar over prototypes
  • Shared methods live on the prototype, not on each instance
  • JavaScriptMedium

    How does the this keyword work in JavaScript?

    this is decided by how a function is called, not where it is written: as a method it is the object before the dot, with new it is the new object, and arrow functions inherit it from the enclosing scope.

    Junior · Mid-level · Functions & Scope
  • JavaScriptMedium

    What is a closure in JavaScript and why is it useful?

    A closure is a function that keeps access to the variables of the scope where it was created, even after that outer function has finished running.

    Junior · Mid-level · Functions & Scope
  • JavaScriptMedium

    What is event delegation in JavaScript?

    Event delegation means attaching one listener to a parent element and using event bubbling to handle events from its children, instead of adding a listener to each child.

    Junior · Mid-level · Browser & DOM
  • JavaScriptMedium

    What is the event loop in JavaScript and how does it work?

    The event loop is the mechanism that lets single-threaded JavaScript handle asynchronous work: it runs the call stack to empty, then runs all queued microtasks (promises), then takes the next task (timers, events) from the queue.

    Mid-level · Senior · Asynchronous Programming