Objects & OOP
Classes
Syntactic sugar over prototypes for object-oriented code.
The class keyword provides a clean syntax for creating objects and handling inheritance, built on top of the prototype system.
A class is a blueprint; each `new` call stamps out a house from it, and `extends` is a blueprint that starts from another blueprint.
Key concepts
1
A constructor initialises instances; methods defined in the body live on the prototype (shared across instances); extends and super set up inheritance. Fields can be private with a # prefix, and static members belong to the class itself rather than instances.
privateconstructorextendssuper#
2
Under the hood there is still a prototype chain — class just makes it readable.
class
javascript
class Account {
#balance = 0; // private field
constructor(owner) { this.owner = owner; }
deposit(n) { this.#balance += n; return this; }
get balance() { return this.#balance; }
}
class Savings extends Account {
addInterest(rate) { this.deposit(this.balance * rate); }
}
const s = new Savings('Ada');
s.deposit(100).addInterest(0.05);
s.balance; // 105