Member-only story
JavaScript classes provide a clean, familiar syntax for object-oriented code. However, JavaScript under the hood still uses prototypal inheritance rather than classical inheritance. In this article, we’ll peel back the class syntax and see how it harness prototypes for reusable and extensible code.
Class Syntax vs. Prototypes
Modern JavaScript gained class syntax, but prototypes still power inheritance:
class Vehicle {
constructor() {
this.passengers = [];
console.log('Vehicle created');
}
addPassenger(p) {
this.passengers.push(p);
}
}
class Car extends Vehicle {}
let car = new Car();
car.addPassenger('Frank');
That class syntax looks straightforward. But how does the Car instance actually inherit from Vehicle behind the scenes? Let’s visualize the prototypes:
null
↑
|
Vehicle.prototype
↑
|
Car.prototype
Car.prototype inherits from Vehicle.prototype. The Car instance then delegates missed properties to Car.prototype. This proto chain enables inheritance.