In JavaScript, two common patterns for organizing code are classes and modules. These patterns can be used independently or together. Understanding both is essential for writing well-structured JS programs.
A class defines a custom data structure that includes both data and behavior. Classes are not values themselves — they must be instantiated using new to create usable objects.
class Page {
constructor(text) {
this.text = text;
}
print() {
console.log(this.text);
}
}
class Notebook {
constructor() {
this.pages = [];
}
addPage(text) {
var page = new Page(text);
this.pages.push(page);
}
print() {
for (let page of this.pages) {
page.print();
}
}
}
var mathNotes = new Notebook();
mathNotes.addPage("Arithmetic: + - * / ...");
mathNotes.addPage("Trigonometry: sin cos tan ...");
mathNotes.print();Here, the Page class stores a text string and defines a print() method. The Notebook class manages an array of pages and provides methods to add and print them.
JavaScript supports class inheritance, allowing child classes to extend parent classes and reuse their behavior:
class Publication {
constructor(title, author, pubDate) {
this.title = title;
this.author = author;
this.pubDate = pubDate;
}
print() {
console.log(`
Title: ${this.title}
By: ${this.author}
${this.pubDate}
`);
}
}
class Book extends Publication {
constructor(details) {
super(details.title, details.author, details.publishedOn);
this.publisher = details.publisher;
this.ISBN = details.ISBN;
}
print() {
super.print();
console.log(`
Publisher: ${this.publisher}
ISBN: ${this.ISBN}
`);
}
}
class BlogPost extends Publication {
constructor(title, author, pubDate, URL) {
super(title, author, pubDate);
this.URL = URL;
}
print() {
super.print();
console.log(this.URL);
}
}Both Book and BlogPost extend Publication and override the print() method. They use super.print() to call the parent method and then add their own output.
Having methods with the same name in both parent and child classes — and choosing the correct one at runtime — is called polymorphism. It adds flexibility to object-oriented design.
Classes and inheritance in JavaScript provide powerful tools for organizing data and behavior. By using classes, developers can create structured, extensible, and readable code. Understanding when and how to use these patterns is key to professional JS development.