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 withObject.getPrototypeOf(obj).Fn.prototypeis a normal property on functions and classes: the object that becomes the[[Prototype]]of instances created withnew 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...inincludes inherited enumerable properties;Object.keysandObject.hasOwndo 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
newdo?" Creates an object linked toFn.prototype, runs the constructor withthisset to it, and returns it. - "Are JavaScript classes real classes?" They are syntax over prototype-based inheritance.
What should you learn before Prototypes?
- 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
- Advanced JavaScript Interview Questions1 question on Prototypes