OOP (Classes & Prototypes)
JavaScript · Reference cheat sheet
OOP (Classes & Prototypes)
JavaScript · Reference cheat sheet
📋 Overview
JavaScript OOP is prototype-based. class syntax is sugar over constructor functions and prototypes, adding inheritance via extends, super, public/private fields, and static members.
🔧 Core concepts
- Class:
constructor, instance methods, getters/setters, fields. - Private:
#field,#method— truly private per class. - Static:
staticprops/methods on the constructor. - Inheritance:
extends,super()before usingthisin subclass constructors. - Prototype:
obj.__proto__/Object.getPrototypeOf; methods live on.prototype. instanceof: walks the prototype chain.
class Animal {
constructor(name) {
this.name = name;
}
speak() {
return `${this.name} makes a noise`;
}
}💡 Examples
class Dog extends Animal {
#tricks = [];
constructor(name, breed) {
super(name);
this.breed = breed;
}
speak() {
return `${super.speak()} — woof`;
}
addTrick(t) {
this.#tricks.push(t);
}
get tricks() {
return [...this.#tricks];
}
static fromJSON(json) {
const data = JSON.parse(json);
return new Dog(data.name, data.breed);
}
}
const d = new Dog("Rex", "lab");
d instanceof Dog; // true
d instanceof Animal; // true
// Mix-in pattern
const Timestamped = (Base) =>
class extends Base {
createdAt = new Date();
};
class Job extends Timestamped(Object) {}
// Prototype check
Object.getPrototypeOf(d) === Dog.prototype;// Composition over deep hierarchies
class Engine {
start() {
return "vroom";
}
}
class Car {
constructor() {
this.engine = new Engine();
}
start() {
return this.engine.start();
}
}⚠️ Pitfalls
- Subclass constructors must call
super()before accessingthis. - Arrow methods as class fields are not on the prototype (per-instance; can’t be easily mocked via proto).
- Private fields are not accessible in subclasses or outside the declaring class.
thisin callbacks needs binding or arrows — class methods are not auto-bound.- Overusing inheritance creates brittle hierarchies — prefer composition.
🔗 Related
- new.md — construction
- objects.md — prototypes & literals
- properties.md — descriptors
- map.md — WeakMap privacy pattern
- error.md — custom Error subclasses
- import_export.md — exporting classes