Skip to main content
Albero Academy

Classes

Model your domain with ES6 classes — constructors, methods, inheritance, static members, and getters and setters.

Chapter 10JavaScript15 min readBeginner friendly
  • #JavaScript
  • #Classes
  • #OOP

Classes are clean syntax for creating objects with shared behaviour — the same prototype mechanism from the last chapter, but readable. If you did the Python or React courses this will feel familiar; it's the standard way to model a domain in larger apps.

Defining a class

a class
class Student {
constructor(name, pkg = 0) { // runs on 'new'
this.name = name;
this.package = pkg;
}
raise(pct) {
this.package *= 1 + pct / 100;
}
summary() {
return `${this.name}: ₹${this.package} LPA`;
}
}
const s = new Student("Aanya", 8);
s.raise(25);
s.summary(); // "Aanya: ₹10 LPA"

Inheritance

extends creates a subclass; super() calls the parent constructor and parent methods:

extends & super
class Person {
constructor(name) { this.name = name; }
greet() { return `Hi, I'm ${this.name}`; }
}
class Mentor extends Person {
constructor(name, company) {
super(name); // call Person's constructor
this.company = company;
}
greet() {
return `${super.greet()} from ${this.company}`;
}
}

Static & private members

static & #private
class MathUtil {
static PI = 3.14159;
static square(n) { return n * n; } // call on the class, not an instance
}
MathUtil.square(5); // 25
class Account {
#balance = 0; // # = truly private
deposit(n) { this.#balance += n; }
get balance() { return this.#balance; }
}

Getters & setters

get/set expose a method as if it were a property — the same idea as Python's @property — letting you compute or validate on access:

accessors
class Circle {
constructor(r) { this.r = r; }
get area() { return Math.PI * this.r ** 2; } // read like a property
set radius(v) {
if (v <= 0) throw new Error("radius must be positive");
this.r = v;
}
}
const c = new Circle(2);
c.area; // 12.566… (no parentheses)
c.radius = 5; // goes through the setter

Practice

Build a Programme class with a name, fee and a discounted-fee getter. Subclass it as Flagship that adds a mentor and overrides summary() with super. Add a static factory method that builds a default programme.

Key takeaways

  1. 01A class has a constructor (runs on new) and methods shared by all instances.
  2. 02extends + super() implement inheritance — call and override parent behaviour.
  3. 03static members belong to the class itself; #name fields are truly private.
  4. 04get/set expose methods as properties for computed or validated access.
  5. 05Classes are readable syntax over JavaScript's prototype mechanism.