JS Classes
JavaScript Classes: Blueprints, Inheritance, and Private Fields
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.
Constructors, Methods, and Inheritance (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).
Modern # Private Fields and Getters
Modern 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}`);
Common Mistakes to Avoid
- Calling a class without
new: RunningAccount("Ada")withoutnewthrows aTypeError. - Accessing
thisbeforesuper()in a subclass: Referencesuper(...)on the first line of any childconstructor(). - Using
_fieldexpecting privacy: An underscore prefix is only a naming hint; use#fieldwhen you want real encapsulation.
Frequently Asked Questions
Are JavaScript classes different from prototype inheritance?
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.
What is a 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.
Can a JavaScript class inherit from multiple parent classes?
No, JavaScript supports single inheritance only (class B extends A). Compose shared behaviors with helper functions or mixins instead.
Unlock Your
Full Potential.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Try it Yourself
Experiment with the code from this lesson in our interactive playground.