JavaScript classes provide clean syntax over prototype-based inheritance for creating reusable object blueprints with shared methods and state. Every class includes a constructor() method that runs automatically when you create an instance with new.
extends)A child class inherits properties and methods from a parent class using extends. Inside the child's constructor(), you must call super(...) before referencing this, which runs the parent constructor first.
You can also mark utility methods as static when they belong to the class itself rather than individual instances, such as User.fromJson(str).
# Private Fields and GettersModern JavaScript (ES2022) supports true private fields prefixed with #. Unlike older _balance naming conventions, #balance is enforced by the engine and cannot be read or modified outside the class body.
class Account {
#balance = 0;
constructor(owner, initialDeposit = 0) {
this.owner = owner;
this.#balance = initialDeposit;
}
deposit(amount) {
if (amount <= 0) throw new Error("Deposit must be positive");
this.#balance += amount;
}
get balance() {
return this.#balance;
}
}
class SavingsAccount extends Account {
constructor(owner, initialDeposit, rate) {
super(owner, initialDeposit);
this.rate = rate;
}
addInterest() {
this.deposit(Number((this.balance * this.rate).toFixed(2)));
}
}
const acct = new SavingsAccount("Nadia", 1000, 0.05);
acct.addInterest();
console.log(`${acct.owner} balance: $${acct.balance}`);
new: Running Account("Ada") without new throws a TypeError.this before super() in a subclass: Reference super(...) on the first line of any child constructor()._field expecting privacy: An underscore prefix is only a naming hint; use #field when you want real encapsulation.Under the hood, ES6 classes still use JavaScript prototypes, yet class syntax makes inheritance, super() calls, and #private fields far cleaner and less error-prone.
static method on a class?A static method attaches to the class constructor itself (MathHelper.clamp()) rather than instances (new MathHelper()), making it ideal for factory functions and helpers.
No, JavaScript supports single inheritance only (class B extends A). Compose shared behaviors with helper functions or mixins instead.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Experiment with the code from this lesson in our interactive playground.