learn deep. ship safe.Practice testsFollow ByteMunSubscribe

Concept

Prototypes

JavaScript's inheritance model: objects delegate missing properties to their prototype.

Prototypes explained

Prototypes are how JavaScript objects share behaviour. Every object has a hidden link to another object, its prototype. When you read a property the object does not have, JavaScript looks it up on the prototype, then the prototype's prototype, until the chain ends at null. Classes are a cleaner syntax for setting up exactly this chain.

How the prototype chain works

const animal = { speak() { return `${this.name} makes a sound`; } };
const dog = Object.create(animal);   // dog's prototype is animal
dog.name = "Rex";
dog.speak();                          // found on animal: "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
}
const tom = new Cat("Tom");
Object.getPrototypeOf(tom) === Cat.prototype; // true

Methods defined in a class are stored once on Cat.prototype and shared by every instance, which saves memory compared with creating them per object. extends links one class's prototype to another's.

prototype versus [[Prototype]]

  • [[Prototype]] is the internal link every object has. Read it with Object.getPrototypeOf(obj).
  • Fn.prototype is a normal property on functions and classes: the object that becomes the [[Prototype]] of instances created with new Fn().

Common mistakes

  • Changing built-in prototypes such as Array.prototype. It affects every array in the program and can clash with future language features.
  • Confusing own and inherited properties in loops. for...in includes inherited enumerable properties; Object.keys and Object.hasOwn do not.
  • Thinking classes copy methods onto each instance. They are shared through the prototype.

What interviewers ask about prototypes

  • "How does property lookup work?" Own properties first, then up the chain to null.
  • "What does new do?" Creates an object linked to Fn.prototype, runs the constructor with this set to it, and returns it.
  • "Are JavaScript classes real classes?" They are syntax over prototype-based inheritance.
Concept map
Learn firstObjects
Part of JavaScriptPrototypes
Then learnClasses

What should you learn before Prototypes?

  1. ObjectsCollections of key–value properties, the building block of most JavaScript data.

What to learn after Prototypes

  • ClassesClasses are syntax over prototypes.

Connections to other concepts

Part of
JavaScript

Practise Prototypes

All topics