JavaScript Classes


JavaScript classes provide a powerful way to work with objects and inheritance, offering a more structured approach than traditional JavaScript prototypes. In this blog, we will explore what classes are, how they work, and their benefits. You’ll also find sample code snippets to understand how to use them in your projects.

What Are JavaScript Classes?

JavaScript classes were introduced in ECMAScript 6 (ES6) to bring a more object-oriented programming (OOP) style to JavaScript. Classes are a blueprint for creating objects with shared properties and methods. They are syntactic sugar over JavaScript’s existing prototype-based inheritance, making it easier to work with objects.

Key Features of JavaScript Classes

  • Constructor Method: A special method used to initialize new objects created from the class.
  • Methods: Functions that belong to the class.
  • Inheritance: The ability to inherit methods and properties from another class using the extends keyword.
  • Encapsulation: Using classes, you can bundle data (properties) and methods that operate on the data into a single unit.

Why Use JavaScript Classes?

JavaScript classes provide a cleaner and more readable syntax than traditional object-oriented code in JavaScript. They enable better organization, structure, and code reusability, making it easier to manage large codebases.


Creating a Simple JavaScript Class

Let's start by creating a basic class. Here's an example of a class that represents a "Person."

Sample Code: Basic Class Definition

class Person {
  // Constructor method
  constructor(name, age) {
    this.name = name;
    this.age = age;
  }

  // Method to display information
  displayInfo() {
    console.log(`${this.name} is ${this.age} years old.`);
  }
}

// Creating an instance of the Person class
const person1 = new Person("Alice", 30);
person1.displayInfo(); // Output: Alice is 30 years old.

Explanation:

  • The constructor is a special method used to initialize the properties name and age.
  • The displayInfo method logs the name and age of the person.

JavaScript Class Inheritance

One of the most powerful features of classes is inheritance. This allows a new class to inherit properties and methods from an existing class. Let's look at how inheritance works in JavaScript.

Sample Code: Inheritance in JavaScript

// Parent class
class Animal {
  constructor(name) {
    this.name = name;
  }

  speak() {
    console.log(`${this.name} makes a sound.`);
  }
}

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

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

  displayBreed() {
    console.log(`${this.name} is a ${this.breed}.`);
  }
}

const dog1 = new Dog("Max", "Golden Retriever");
dog1.speak(); // Output: Max barks.
dog1.displayBreed(); // Output: Max is a Golden Retriever.

Explanation:

  • The Dog class extends the Animal class and inherits the speak method.
  • The super(name) is used to call the constructor of the parent class (Animal).
  • The speak method is overridden to provide specific functionality for the Dog class.

JavaScript Getters and Setters in Classes

JavaScript classes also support getters and setters, which allow you to define special methods to access or modify properties. These are useful for encapsulating data and providing controlled access.

Sample Code: Getters and Setters

class Car {
  constructor(brand, model) {
    this.brand = brand;
    this.model = model;
  }

  // Getter method for full car info
  get carInfo() {
    return `${this.brand} ${this.model}`;
  }

  // Setter method to update the car model
  set updateModel(newModel) {
    this.model = newModel;
  }
}

const myCar = new Car("Toyota", "Corolla");
console.log(myCar.carInfo); // Output: Toyota Corolla

myCar.updateModel = "Camry"; // Update the model
console.log(myCar.carInfo); // Output: Toyota Camry

Explanation:

  • The carInfo getter provides a formatted string of the car's brand and model.
  • The updateModel setter allows you to change the model of the car.

Static Methods in JavaScript Classes

Static methods are functions that belong to the class itself rather than instances of the class. You can use them to perform operations that are not dependent on individual objects.

Sample Code: Static Method Example

class MathOperations {
  // Static method
  static add(x, y) {
    return x + y;
  }

  static subtract(x, y) {
    return x - y;
  }
}

console.log(MathOperations.add(5, 3)); // Output: 8
console.log(MathOperations.subtract(5, 3)); // Output: 2

Explanation:

  • The static methods add and subtract are called on the class itself rather than on instances of the class.

Advanced Class Features: Private Fields and Methods

As of ES2022, JavaScript classes support private fields and methods, which allow you to define properties and methods that cannot be accessed outside the class.

Sample Code: Private Fields

class User {
  #password; // Private field

  constructor(username, password) {
    this.username = username;
    this.#password = password;
  }

  // Method to access private field
  checkPassword(inputPassword) {
    if (this.#password === inputPassword) {
      console.log("Password is correct.");
    } else {
      console.log("Incorrect password.");
    }
  }
}

const user1 = new User("john_doe", "1234");
user1.checkPassword("1234"); // Output: Password is correct.

Explanation:

  • The #password field is a private field, and it cannot be accessed directly from outside the class.