In JavaScript, Classes are a blueprint for creating objects. Introduced in ECMAScript 2015 (ES6), they provide a much cleaner and more intuitive syntax for implementing Object-Oriented Programming (OOP) compared to the older, more complex prototype-based inheritance.

Despite the new syntax, it is important to remember that JavaScript classes are primarily “syntactic sugar” over the existing prototype system. They do not introduce a new object-oriented inheritance model to the language.

1. Basic Class Anatomy

A class is defined using the class keyword followed by a name (by convention, ClassNames use PascalCase).

The Constructor

The constructor is a special method used for creating and initializing an object created with a class. There can only be one constructor in a class.

JavaScript
class Car {
  constructor(brand, model) {
    this.brand = brand; // "this" refers to the instance being created
    this.model = model;
    this.speed = 0;
  }

  // Method defined on the prototype
  accelerate(amount) {
    this.speed += amount;
    console.log(`${this.brand} is now going ${this.speed} km/h`);
  }
}

const myCar = new Car('Tesla', 'Model 3');
myCar.accelerate(50);

2. Encapsulation: Private and Static Members

Private Fields (#)

Traditionally, JavaScript had no way to truly hide data. Now, by prefixing a variable name with a hash #, you make it private. Private fields cannot be accessed or modified from outside the class.

JavaScript
class BankAccount {
  #balance = 0; // Private field

  deposit(amount) {
    this.#balance += amount;
  }

  showBalance() {
    return `Your balance is $${this.#balance}`;
  }
}

const account = new BankAccount();
// console.log(account.#balance); // Error: Private field '#balance' must be declared in an enclosing class

Static Methods and Properties

Static members are defined using the static keyword. They belong to the class itself, not to the instances created from the class. They are often used for utility functions related to the class.

JavaScript
class MathUtils {
  static PI = 3.14159;

  static calculateCircleArea(radius) {
    return this.PI * (radius ** 2);
  }
}

console.log(MathUtils.calculateCircleArea(10)); // Accessed via Class name, not "new MathUtils()"

3. Inheritance: extends and super

Inheritance allows a class (child) to acquire the properties and methods of another class (parent).

  • extends: Used to create a child class.
  • super(): Used inside the constructor to call the parent’s constructor. It must be called before using this.

JavaScript

class Animal {
  constructor(name) {
    this.name = name;
  }
  speak() {
    console.log(`${this.name} makes a noise.`);
  }
}

class Dog extends Animal {
  constructor(name, breed) {
    super(name); // Call the parent constructor
    this.breed = breed;
  }

  speak() {
    console.log(`${this.name} barks!`); // Overriding parent method
  }
}

const myDog = new Dog('Rex', 'German Shepherd');
myDog.speak(); // "Rex barks!"

4. Getters and Setters

Accessors allow you to define methods that execute when a property is accessed or changed, providing a way to validate data or compute values dynamically.

JavaScript
class User {
  constructor(firstName, lastName) {
    this.firstName = firstName;
    this.lastName = lastName;
  }

  get fullName() {
    return `${this.firstName} ${this.lastName}`;
  }

  set fullName(value) {
    [this.firstName, this.lastName] = value.split(' ');
  }
}

const user = new User('Jane', 'Doe');
console.log(user.fullName); // "Jane Doe"
user.fullName = "John Smith"; // Calls the setter

5. Private Fields (#)

In modern JavaScript (ES2020+), you can create truly private properties and methods by prefixing them with a hash #. These cannot be accessed or modified from outside the class.

JavaScript
class BankAccount {
  #balance = 0; // Private field

  deposit(amount) {
    this.#balance += amount;
  }

  checkBalance() {
    return this.#balance;
  }
}

const account = new BankAccount();
account.deposit(100);
console.log(account.checkBalance()); // 100
// console.log(account.#balance); // Syntax Error: Private field '#balance' must be 

Categorized in:

Javascript,