Glossary / Prototypal inheritance
Prototypal inheritance
Prototypal inheritance reuses behavior by linking one object to another object from which missing properties can be read. JavaScript’s class syntax provides familiar constructor and inheritance syntax over this object-based mechanism; instances still delegate method lookup through prototype objects. Understanding the underlying model helps explain this, overriding, instanceof, and memory sharing.
Delegation with prototypes
const vehicle = { move() { return `${this.name} moves`; } };
const bike = Object.create(vehicle);
bike.name = "Bike";
bike.move(); // "Bike moves"
The method is stored once on the prototype and used by inheriting objects. The receiver remains the object before the dot. An own property shadows an inherited property, enabling an override without changing the shared prototype. Changing a prototype later can alter behavior for all objects that inherit from it.
Class inheritance formalizes this pattern: Child.prototype inherits from Parent.prototype, and the constructor objects themselves are linked for static inheritance. Deep hierarchies can make behavior and initialization order hard to reason about. Composition often works better when a type needs capabilities but is not truly substitutable for another type. Follow Liskov-style contracts: a subtype should preserve expectations callers have of the base.
Risks and practical choices
Do not mutate built-in prototypes in application code. Validate dynamic property merges to avoid prototype-pollution vulnerabilities. Use classes when nominal constructors and lifecycle are clear; use composition for orthogonal capabilities; use plain objects for lightweight records.
Interview questions
- Are class methods copied into instances? Normally no; they live on the class prototype.
- What is
thisin an inherited method call? The actual receiver, often the child instance. - When prefer composition? When behavior reuse does not imply a true subtype relationship.
- What is prototype pollution? Attacker-controlled property paths mutate prototype state and influence unrelated objects.