← JS Mastery | Module 7: ES6+ Modern JS Classes, Inheritance & Private Fields
Module 7

Classes, Inheritance & Private Fields

⏱ 24 min read ● Intermediate 🆓 Free

ES6 Classes

class Animal {
  constructor(name, sound) {
    this.name = name;
    this.sound = sound;
  }
  
  speak() {
    return this.name + " says " + this.sound + "!";
  }
  
  static create(name, sound) {
    return new Animal(name, sound);
  }
  
  get info() { return this.name + " (" + this.sound + ")"; }
}

const dog = new Animal("Rex", "Woof");
console.log(dog.speak());  // Rex says Woof!

Inheritance

class Dog extends Animal {
  constructor(name, breed) {
    super(name, "Woof");  // call parent constructor
    this.breed = breed;
  }
  
  speak() {
    return super.speak() + " *wags tail*";  // call parent method
  }
  
  fetch(item) { return this.name + " fetches " + item + "!"; }
}

const rex = new Dog("Rex", "Labrador");
console.log(rex.speak());  // Rex says Woof! *wags tail*
console.log(rex instanceof Dog);    // true
console.log(rex instanceof Animal); // true

Private Fields & Static

class BankAccount {
  #balance;  // private — # prefix
  
  constructor(initial) { this.#balance = initial; }
  
  deposit(amount) {
    this.#balance += amount;
    return this;
  }
  
  withdraw(amount) {
    if (amount > this.#balance) throw new Error("Insufficient funds");
    this.#balance -= amount;
    return this;
  }
  
  get balance() { return this.#balance; }
}

const acc = new BankAccount(100);
acc.deposit(50).withdraw(30);
console.log(acc.balance);  // 120
// acc.#balance  // SyntaxError — truly private!

// Static:
class Counter {
  static #count = 0;
  static increment() { return ++Counter.#count; }
  static getCount() { return Counter.#count; }
}
Counter.increment();
Counter.increment();
console.log(Counter.getCount());  // 2

⚡ Key Takeaways

🎯 Practice Exercises

EXERCISE 1

Create a Shape base class with abstract area() and perimeter(). Extend with Circle, Rectangle, Triangle. Add a static compare(a, b) that returns the larger shape by area.

← ES Modules