JavaScript Classes

In JavaScript, classes provide a clearer and more structured way to create objects and manage inheritance. Introduced in ECMAScript 2015 (ES6), classes are a syntactical sugar over JavaScript’s existing prototype-based inheritance, making it easier to work with objects and inheritance.

1. Defining a Class

A class is defined using the class keyword, followed by the class name and a block of methods. The constructor method is a special method for creating and initializing an object instance of the class.

Example: Basic Class Definition

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

    greet() {
        console.log(`Hello, my name is ${this.name} and I am ${this.age} years old.`);
    }
}

const person1 = new Person('Alice', 25);
person1.greet();  // Output: Hello, my name is Alice and I am 25 years old.

Try It Now

Explanation:

  • The Person class has a constructor method that initializes name and age properties.
  • The greet method is a regular method inside the class, used to display a greeting message.

2. Creating Instances of a Class

Instances of a class are created using the new keyword, which calls the constructor method to initialize the object.

Example: Creating Instances

const person2 = new Person('Bob', 30);
person2.greet();  // Output: Hello, my name is Bob and I am 30 years old.

Try It Now

Explanation:

  • person2 is an instance of the Person class, with properties and methods defined in the class.

3. Class Methods

Methods in a class are functions defined inside the class body. They are invoked on instances of the class.

Example: Defining Class Methods

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

    getDetails() {
        return `${this.year} ${this.make} ${this.model}`;
    }
}

const car1 = new Car('Toyota', 'Camry', 2021);
console.log(car1.getDetails());  // Output: 2021 Toyota Camry

Try It Now

4. Getters and Setters

Getters and setters allow you to define methods that behave like properties, making it easier to control access to an object’s properties.

Example: Getters and Setters

class Rectangle {
    constructor(width, height) {
        this.width = width;
        this.height = height;
    }

    get area() {
        return this.width * this.height;
    }

    set width(value) {
        if (value <= 0) throw new Error('Width must be positive.');
        this._width = value;
    }

    get width() {
        return this._width;
    }
}

const rect = new Rectangle(10, 20);
console.log(rect.area);  // Output: 200
rect.width = 15;
console.log(rect.area);  // Output: 300

Try It Now

Explanation:

  • The area property is a getter, computed from width and height.
  • The width property has both a getter and a setter, allowing control over how the width is set.

5. Static Methods

Static methods belong to the class itself, not instances of the class. They are useful for utility functions related to the class.

Example: Static Methods

class MathUtilities {
    static add(a, b) {
        return a + b;
    }
}

console.log(MathUtilities.add(5, 10));  // Output: 15

Try It Now

Explanation:

  • The add method is a static method of the MathUtilities class and is called directly on the class.

6. Inheritance with Classes

Classes support inheritance, allowing one class to inherit properties and methods from another.

Example: Class Inheritance

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

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

class Dog extends Animal {
    makeSound() {
        console.log(`${this.name} barks.`);
    }
}

const dog = new Dog('Rex');
dog.makeSound();  // Output: Rex barks.

Try It Now

Explanation:

  • Dog class extends the Animal class, inheriting its properties and methods but overriding the makeSound method.

7. Using super Keyword

The super keyword is used to call the constructor or methods of a parent class.

Example: Using super

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

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

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

    makeSound() {
        super.makeSound();  // Call the parent class method
        console.log(`${this.name} meows.`);
    }
}

const cat = new Cat('Whiskers', 'Siamese');
cat.makeSound();  // Output: Whiskers makes a sound. Whiskers meows.

Try It Now

Explanation:

  • super(name) calls the constructor of the Animal class.
  • super.makeSound() calls the makeSound method from the Animal class.

8. Private Fields (ES2022)

Private fields are properties of a class that are not accessible from outside the class. They are prefixed with #.

Example: Private Fields

class BankAccount {
    #balance = 0;

    constructor(accountHolder) {
        this.accountHolder = accountHolder;
    }

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

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

const account = new BankAccount('John Doe');
account.deposit(100);
console.log(account.getBalance());  // Output: 100

Try It Now

Explanation:

  • #balance is a private field and cannot be accessed directly outside the class.

Summary of JavaScript Classes

  • Classes provide a cleaner, more organized way to create objects and manage inheritance in JavaScript.
  • The constructor method initializes new object instances.
  • Methods, getters/setters, and static methods are essential parts of classes.
  • Classes support inheritance and the super keyword for creating more complex hierarchies.
  • Private fields provide a way to encapsulate data within a class.

By understanding classes, you can leverage the full power of object-oriented programming in JavaScript, making your code more modular, reusable, and maintainable.