JavaScript Classes

JavaScript classes are a template for creating objects with shared properties and methods. They provide a clear and concise syntax for defining and instantiating objects. This tutorial covers the basics of JavaScript classes, including constructors, methods, and inheritance.

Introduction to Classes

Classes in JavaScript are introduced in ECMAScript 2015 (ES6) and provide a way to create reusable and extendable objects. The class syntax is a syntactic sugar over JavaScript's existing prototype-based inheritance.

Defining a Class

To define a class, use the `class` keyword followed by the class name and curly braces. Inside the class, you can define a constructor and methods.


// Example of defining a class
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 Instances

Once a class is defined, you can create instances of it using the `new` keyword. Each instance has its own properties and methods.


// Example of creating an instance
const person1 = new Person('Alice', 30);
person1.greet(); // Outputs: Hello, my name is Alice and I am 30 years old.

                

Inheritance

JavaScript classes support inheritance, allowing you to create a class that extends another class. The child class inherits properties and methods from the parent class.


// Example of inheritance
class Employee extends Person {
    constructor(name, age, jobTitle) {
        super(name, age); // Call the parent class's constructor
        this.jobTitle = jobTitle;
    }

    describe() {
        console.log(`I am ${this.name}, a ${this.jobTitle}.`);
    }
}

const employee1 = new Employee('Bob', 25, 'Software Developer');
employee1.greet(); // Outputs: Hello, my name is Bob and I am 25 years old.
employee1.describe(); // Outputs: I am Bob, a Software Developer.

                

Static Methods

Static methods are called on the class itself rather than on instances of the class. They are useful for utility functions that are related to the class but do not need access to instance properties.


// Example of a static method
class MathHelper {
    static add(x, y) {
        return x + y;
    }
}

console.log(MathHelper.add(5, 3)); // Outputs: 8

                

Private Fields

JavaScript now supports private fields, which are variables that are accessible only within the class they are defined in. This helps to encapsulate the data and prevent accidental modification from outside the class.


// Example of private fields
class BankAccount {
    #balance; // Private field

    constructor(initialBalance) {
        this.#balance = initialBalance;
    }

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

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

const account = new BankAccount(100);
account.deposit(50);
console.log(account.getBalance()); // Outputs: 150
// console.log(account.#balance); // SyntaxError: Private field '#balance' must be declared in an enclosing class