Classes
When you need many objects of the same shape, such as SACCO accounts, students or products, writing each one by hand is repetitive. A class is a blueprint: you describe the data and methods once, then create as many objects (called instances) as you need with new. Classes also support inheritance, so one class can build on another.
Defining a class
A class has a constructor, which runs when you create an instance and sets up its data, and methods, which every instance can use. Inside, this refers to the instance being worked on.
class Student {
constructor(name, county) {
this.name = name;
this.county = county;
}
introduce() {
return `Hi, I'm ${this.name} from ${this.county}.`;
}
}
const amina = new Student("Amina", "Kisumu");
const juma = new Student("Juma", "Mombasa");
console.log(amina.introduce());
console.log(juma.name);
console.log(amina instanceof Student);
Class names use PascalCase by convention. Methods are shared: there is one introduce function on the class's prototype, used by every instance, rather than a copy inside each object. That is how JavaScript's prototype system works underneath, and classes are a clearer way to write it.
Forgetting new. Student("Amina", "Kisumu") throws "TypeError: Class constructor Student cannot be invoked without 'new'". Also note that, unlike function declarations, classes can't be used before the line that defines them.
Fields, private fields, getters and static members
Modern classes can declare fields directly in the class body. A field whose name starts with # is private: only code inside the class can read or change it. A getter (get) looks like a property from outside but runs a method. Static members belong to the class itself, not to each instance.
class Account {
owner;
#balance = 0;
static count = 0;
constructor(owner, deposit = 0) {
this.owner = owner;
this.#balance = deposit;
Account.count++;
}
deposit(amount) {
if (amount <= 0) throw new RangeError("Deposit must be positive");
this.#balance += amount;
return this; // returning this allows chaining
}
get balance() {
return this.#balance;
}
describe() {
return `${this.owner}: KES ${this.#balance}`;
}
}
const amina = new Account("Amina", 1000);
const baraka = new Account("Baraka");
amina.deposit(500).deposit(250);
console.log(amina.describe());
console.log(baraka.balance);
console.log(Account.count);
Because #balance is private, the only way to change it is through deposit, which checks the amount. Writing amina.#balance = 1000000 outside the class is a SyntaxError, so the whole script refuses to run. This protection is called encapsulation. The getter means amina.balance can be read but, with no matching setter, not assigned.
Inheritance with extends and super
A class can extend another. The child class gets all the parent's methods and can add its own or override existing ones. In the child's constructor you must call super(...), which runs the parent's constructor, before using this. Inside methods, super.method() calls the parent's version.
class SavingsAccount extends Account {
constructor(owner, deposit, ratePercent) {
super(owner, deposit); // run Account's constructor first
this.ratePercent = ratePercent;
}
addInterest() {
const interest = Math.round(this.balance * this.ratePercent / 100);
this.deposit(interest);
return interest;
}
describe() { // override, reusing the parent's version
return `${super.describe()} (savings at ${this.ratePercent}%)`;
}
}
const wanjiru = new SavingsAccount("Wanjiru", 2000, 5);
console.log(wanjiru.addInterest());
console.log(wanjiru.describe());
console.log(wanjiru instanceof SavingsAccount, wanjiru instanceof Account);
Notice that SavingsAccount reads the balance through the balance getter. Private fields are private to the class that declares them, so even a child class can't write this.#balance.
new. A child class built with extends inherits the parent's methods, so its instances can use both sets.Using this in a child constructor before calling super() throws a ReferenceError ("Must call super constructor in derived class before accessing 'this'"). Make super(...) the first line of the constructor.
Methods as callbacks: keeping this
When you pass a method to addEventListener or setTimeout, it is called without its object, so this is lost. An arrow function field fixes it, because arrow functions take this from where they are defined (see Arrow Functions):
class Counter {
count = 0;
increment = () => { // arrow function field: this is always the instance
this.count++;
console.log(this.count);
};
}
const clicks = new Counter();
setTimeout(clicks.increment, 100);
setTimeout(clicks.increment, 200);
With a normal method (increment() {...}), this would be undefined inside the timer callback and this.count++ would throw a TypeError. Another fix is setTimeout(() => clicks.increment(), 100).
Key points
- A class is a blueprint;
new ClassName(...)runs theconstructorand returns an instance. - Fields declare data,
#privatefields are hidden from outside code,getcreates computed properties andstaticmembers belong to the class. extendscreates a child class; callsuper(...)before usingthis, andsuper.method()to reuse the parent's version.- Methods lose
thiswhen passed as callbacks; use arrow function fields or wrap the call in an arrow function.
Tip: use the ← and → keys to move between pages.
