JavaScript Classes

Welcome to TheCodingCollege.com! JavaScript classes, introduced in ES6, provide a clean and intuitive way to implement object-oriented programming (OOP) in JavaScript. While classes are essentially syntactical sugar over JavaScript’s existing prototypal inheritance, they make code more readable and structured.

In this tutorial, we’ll cover everything you need to know about JavaScript classes: from their basics to advanced concepts.

What Are JavaScript Classes?

A class is a blueprint for creating objects. It encapsulates data (properties) and behavior (methods) in one place.

Syntax:

class ClassName {
    constructor(parameters) {
        // Initialization code
    }
    methodName() {
        // Method code
    }
}

Creating a Class

Example:

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.`);
    }
}

// Creating an instance
const alice = new Person('Alice', 30);
alice.greet(); // Output: Hello, my name is Alice and I am 30 years old.

Key Features of JavaScript Classes

1. The constructor Method

The constructor is a special method used for initializing an object’s properties. It is called automatically when a new instance is created.

class Car {
    constructor(brand, model) {
        this.brand = brand;
        this.model = model;
    }
    showDetails() {
        console.log(`This car is a ${this.brand} ${this.model}.`);
    }
}
const car = new Car('Toyota', 'Corolla');
car.showDetails(); // Output: This car is a Toyota Corolla.

2. Instance Methods

Methods defined inside a class are called instance methods. They are available to all objects created from the class.

class Calculator {
    add(a, b) {
        return a + b;
    }
}
const calc = new Calculator();
console.log(calc.add(5, 3)); // Output: 8

3. Static Methods

Static methods belong to the class itself and cannot be called on instances.

Example:

class MathUtil {
    static square(num) {
        return num * num;
    }
}
console.log(MathUtil.square(4)); // Output: 16

4. Inheritance

Classes can extend other classes to inherit properties and methods.

Example:

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

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

const dog = new Dog('Buddy');
dog.speak(); // Output: Buddy barks.

5. Getters and Setters

You can use get and set to define methods that act as properties.

Example:

class Rectangle {
    constructor(width, height) {
        this.width = width;
        this.height = height;
    }
    get area() {
        return this.width * this.height;
    }
    set dimensions({ width, height }) {
        this.width = width;
        this.height = height;
    }
}
const rect = new Rectangle(4, 5);
console.log(rect.area); // Output: 20
rect.dimensions = { width: 10, height: 2 };
console.log(rect.area); // Output: 20

6. Private Fields and Methods

Private fields and methods are declared with a # symbol and are accessible only within the class.

Example:

class BankAccount {
    #balance = 0;
    deposit(amount) {
        if (amount > 0) this.#balance += amount;
    }
    getBalance() {
        return this.#balance;
    }
}
const account = new BankAccount();
account.deposit(100);
console.log(account.getBalance()); // Output: 100
// console.log(account.#balance); // Error: Private field

7. Using super

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

Example:

class Vehicle {
    constructor(type) {
        this.type = type;
    }
    start() {
        console.log(`${this.type} is starting.`);
    }
}

class Car extends Vehicle {
    constructor(type, brand) {
        super(type);
        this.brand = brand;
    }
    start() {
        super.start();
        console.log(`The car brand is ${this.brand}.`);
    }
}

const car = new Car('Vehicle', 'Toyota');
car.start();
// Output: 
// Vehicle is starting.
// The car brand is Toyota.

Why Use Classes?

  • Readability: Classes make your code cleaner and more organized.
  • Reusability: Inheritance allows you to reuse properties and methods.
  • Encapsulation: You can keep data private and expose only necessary methods.

Common Use Cases for Classes

1. Creating Reusable Components

Classes are perfect for creating reusable components in applications, like user interfaces or data models.

2. Modeling Real-World Objects

They help map real-world entities to code. For example, classes like Car, Animal, or User.

3. Encapsulation of Logic

Classes can bundle related logic and data into one neat unit.

Why Learn Classes at TheCodingCollege.com?

At TheCodingCollege.com, we provide:

  • Clear Explanations: Learn the fundamentals and advanced topics of classes with examples.
  • Interactive Exercises: Practice creating classes, inheritance, and using getters/setters.
  • Expert Support: Gain insights into best practices for using JavaScript classes.

Conclusion

JavaScript classes offer a structured and powerful way to implement object-oriented programming. By mastering classes, you can write scalable, reusable, and maintainable code for complex applications.

Leave a Comment