A class is a blueprint for making objects that share the same shape and behaviour. Instead of writing out a fresh object literal for every bank account or every shape, you describe the structure once and create as many instances as you need with new. Classes also support inheritance, so a Circle can reuse everything a general Shape already does.
In this lesson you will learn
- Writing a class with a
constructorand methods - Creating objects with
new - Private fields with
#and getters - Inheritance with
extendsandsuper - Overriding methods and
staticmethods
Constructor, Methods and Private Fields
class BankAccount {
#balance = 0; // private field
constructor(owner) {
this.owner = owner;
}
deposit(amount) {
if (amount <= 0) throw new Error("Deposit must be positive");
this.#balance += amount;
return this; // allows chaining
}
withdraw(amount) {
if (amount > this.#balance) {
console.log(`${this.owner}: not enough money`);
return this;
}
this.#balance -= amount;
return this;
}
get balance() { // getter: read like a property
return this.#balance;
}
}
const acc = new BankAccount("Fatima");
acc.deposit(5000).withdraw(1200).withdraw(10000);
console.log(acc.owner, acc.balance);
console.log(acc instanceof BankAccount);
// console.log(acc.#balance); // SyntaxError: private field
Output
Fatima: not enough money
Fatima 3800
true
constructor()runs automatically when you writenew BankAccount("Fatima"). It sets up the new object’s starting data onthis.- Methods such as
deposit()are written inside the class without thefunctionkeyword. Every instance shares them. #balanceis a private field. Code outside the class cannot read or change it, so the balance can only move throughdepositandwithdraw, which check the amounts. This is encapsulation.get balance()is a getter: it runs a method but is read like a property,acc.balance, with no parentheses.- Returning
thisfrom a method allows chaining:acc.deposit(5000).withdraw(1200). instanceofchecks whether an object was made from a class.
Inheritance with extends
class Shape {
constructor(name) {
this.name = name;
}
area() {
return 0;
}
describe() {
return `${this.name} with area ${this.area().toFixed(2)}`;
}
}
class Circle extends Shape {
constructor(r) {
super("Circle"); // call the parent constructor first
this.r = r;
}
area() { // override the parent method
return Math.PI * this.r ** 2;
}
}
class Rectangle extends Shape {
constructor(w, h) {
super("Rectangle");
this.w = w;
this.h = h;
}
area() {
return this.w * this.h;
}
static square(side) { // called on the class, not an object
return new Rectangle(side, side);
}
}
const shapes = [new Circle(3), new Rectangle(4, 5), Rectangle.square(6)];
for (const s of shapes) console.log(s.describe());
console.log(shapes[0] instanceof Shape);
Output
Circle with area 28.27
Rectangle with area 20.00
Rectangle with area 36.00
true
class Circle extends ShapemakesCirclea child class that inheritsdescribe()fromShape.- A child constructor must call
super(...)before usingthis; it runs the parent’s constructor. - Defining
area()again in the child overrides the parent version.describe()callsthis.area(), so each shape automatically uses its own formula. Treating different objects through one shared interface like this is called polymorphism. - A
staticmethod belongs to the class itself:Rectangle.square(6). It is often used as a convenient “factory” for creating instances.
Classes vs Object Literals
| Use | When |
|---|---|
Object literal { } | One-off data, configuration, JSON from a server |
| Class | Many objects with the same structure and behaviour, or when you want private state and inheritance |
Under the hood, JavaScript classes are built on prototypes: methods live on BankAccount.prototype and every instance links to it. The class syntax is a cleaner way to write the same thing.
Common Mistakes
- Forgetting
new: callingBankAccount("x")throws “Class constructor cannot be invoked without ‘new'”. - Using
thisbeforesuper()in a child constructor, which throws a ReferenceError. - Passing a method as a callback, such as
button.onclick = acc.deposit, which losesthis. Wrap it:() => acc.deposit(100). - Putting commas between methods as in an object literal; class bodies do not use them.
Practice Exercises
Exercise 1. Create a Student class with a name and a marks array, and a method average().
Show answer
class Student {
constructor(name, marks) {
this.name = name;
this.marks = marks;
}
average() {
return this.marks.reduce((s, m) => s + m, 0) / this.marks.length;
}
}
console.log(new Student("Rina", [80, 90, 70]).average()); // 80
Exercise 2. Make a SavingsAccount that extends BankAccount and adds addInterest(rate).
Show answer
class SavingsAccount extends BankAccount {
addInterest(rate) {
return this.deposit(this.balance * rate);
}
}
const s = new SavingsAccount("Tanim").deposit(1000).addInterest(0.05);
console.log(s.balance); // 1050
The child cannot touch #balance directly, so it uses the public getter and deposit().
Frequently Asked Questions
Are JavaScript classes the same as Java classes?
They look similar, but JavaScript classes are built on prototypes, are created at run time, and allow only single inheritance through extends. There are no interfaces or method overloading.
When were private fields added?
Private #fields became part of the language in ES2022 and work in all modern browsers and in current Node.js versions.
Summary
- A class is a blueprint;
newcreates instances and runs the constructor. #privatefields protect data; getters expose it safely.extendsandsuperbuild child classes that reuse and override behaviour.staticmethods belong to the class itself.
Next: JavaScript Error Handling.
