Chapter 5 Cheatsheet: Classes
This cheatsheet summarizes the core mechanics of object-oriented classes in JavaScript covered in Chapter 5.
Basic Classes
Classes act as blueprints for generating multiple consistent object instances. The constructor runs automatically upon instantiation.
class User {
constructor(name) {
this.name = name;
}
}
const u = new User("Alice");
Encapsulation (Private Properties)
By default, all properties are public. Prefix a property with a hash (#) to make it completely private and inaccessible from outside the class.
class Vault {
#password; // Must be declared at the top level
constructor(pw) {
this.#password = pw;
}
}
Static Members
static properties and methods belong to the Class definition itself, not the individual instances. Great for utility functions or global counters.
class MathUtils {
static add(a, b) {
return a + b;
}
}
// Called directly on the class
MathUtils.add(5, 10);
Getters and Setters
Act like standard properties from the outside, but execute function logic on the inside. Useful for data validation.
class User {
set age(value) {
if (value < 0) throw new Error("Invalid age");
this._age = value;
}
get age() {
return this._age;
}
}
Inheritance (extends and super)
extends: Allows a child class to inherit from a parent class.- Method Overriding: Declaring a method in the child with the same name as the parent overrides the parent’s behavior.
super(): Calls the parent constructor. Must be called before usingthisin a child constructor.super.methodName(): Calls the parent’s version of a method.
class Animal {
constructor(name) { this.name = name; }
speak() { return "Noise"; }
}
class Dog extends Animal {
constructor(name, breed) {
super(name); // Must be called first!
this.breed = breed;
}
speak() {
return super.speak() + " Woof!";
}
}