Skip to main content
Published on

Classes and Constructors in JavaScript

Share:

Introduction

Classes in JavaScript, introduced in ES6, provide a clearer and more concise way to create objects and organise code. This article explores the definition and use of classes and constructors in JavaScript, highlighting how they can be used to improve the structure and clarity of your code.

What are Classes?

In JavaScript, a class is a kind of template for creating objects. It encapsulates data and functionality that are common to the object, acting as a blueprint.

Basic Class Syntax

A class in JavaScript is declared using the class keyword.

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

  showInfo() {
    console.log(`${this.name} is ${this.age} years old.`);
  }
}

Constructors

The constructor method is a special type of method for creating and initialising an object created with a class.

Using the Constructor

The constructor is called at the moment the object is created with the new keyword.

let person = new Person('Ana', 30);
person.showInfo(); // Ana is 30 years old.

Class Methods

Classes can also contain methods. These are functions associated with the class.

Defining Methods

Methods are defined inside the class and can be invoked by its objects.

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

  showDetails() {
    console.log(`Car: ${this.brand} ${this.model}`);
  }
}

let myCar = new Car('Toyota', 'Corolla');
myCar.showDetails(); // Car: Toyota Corolla

Class Properties

JavaScript does not directly support class properties, but you can simulate this using getters and setters.

Getters and Setters

Getters and setters allow you to control how the properties of a class are accessed and modified.

class Square {
  constructor(side) {
    this._side = side;
  }

  get area() {
    return this._side * this._side;
  }

  set side(newSide) {
    this._side = newSide;
  }
}

let square = new Square(4);
console.log(square.area); // 16
square.side = 5;
console.log(square.area); // 25

Best Practices and Tips

  1. Clear Naming: Choose clear and descriptive names for classes and their members.
  2. Encapsulation: Use classes to encapsulate related data and methods.
  3. Keep It Simple: Avoid excessively large and complex classes; split responsibilities when necessary.

Conclusion

Classes and constructors in JavaScript offer a powerful and elegant way to create and manage more complex objects. They provide a clear structure and a more familiar syntax for developers with experience in object-oriented languages, helping to organise and modularise code.

Happy coding!