Classes

Classes

Classes in JavaScript are a fundamental feature introduced in ECMAScript 6 (ES6) that allows you to create objects with shared properties and methods. JavaScript classes are primarily syntactic sugar over the existing prototype-based inheritance system, providing a cleaner and more familiar way to define object constructors and prototypes.

1. Class Declaration

To declare a class in JavaScript, use the class keyword followed by the name of the class:

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

In this example, a Car class is defined with a constructor method that sets the make and model properties of the car object.

2. Class Constructor

The constructor method is a special method used to initialize object instances when the class is instantiated. You can pass arguments to the constructor to set the initial state of the object:

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

const myCar = new Car('Toyota', 'Camry');
console.log(myCar.make);   // Output: Toyota
console.log(myCar.model);  // Output: Camry

3. Class Methods

You can define methods within a class, which are functions that can be called on class instances:

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

  startEngine() {
    console.log('Engine started.');
  }
}

const myCar = new Car('Toyota', 'Camry');
myCar.startEngine(); // Output: Engine started.

4. Static Methods

Static methods are methods that belong to the class itself and not to instances of the class. You define static methods using the static keyword:

class MathUtils {
  static add(x, y) {
    return x + y;
  }
}

const sum = MathUtils.add(5, 3);
console.log(sum); // Output: 8

5. Inheritance

Classes in JavaScript support inheritance, allowing you to create a new class based on an existing class, inheriting its properties and methods. To create a subclass, you use the extends keyword:

class ElectricCar extends Car {
  constructor(make, model, batteryCapacity) {
    super(make, model); // Call the superclass constructor
    this.batteryCapacity = batteryCapacity;
  }

  chargeBattery() {
    console.log('Battery charging...');
  }
}

const myElectricCar = new ElectricCar('Tesla', 'Model S', '100 kWh');
myElectricCar.chargeBattery();

In this example, the ElectricCar class extends the Car class, inheriting its make and model properties and the startEngine method. It adds a new property, batteryCapacity, and a chargeBattery method.

6. Getters and Setters

You can define getters and setters within a class to control access to properties. Getters allow you to retrieve a property's value, while setters allow you to modify it. Here's an example:

class Circle {
  constructor(radius) {
    this._radius = radius;
  }

  get radius() {
    return this._radius;
  }

  set radius(newRadius) {
    if (newRadius >= 0) {
      this._radius = newRadius;
    } else {
      console.error('Radius cannot be negative.');
    }
  }

  get area() {
    return Math.PI * this._radius ** 2;
  }
}

const circle = new Circle(5);
console.log(circle.radius); // Output: 5
circle.radius = 7;           // Set the radius using the setter
console.log(circle.radius); // Output: 7
console.log(circle.area);    // Output: 153.93804002589985

In this example, the Circle class has a getter and a setter for the radius property and a getter for the area.

7. Best Practices

  • Use classes to create object blueprints that encapsulate data and behavior.

  • Follow naming conventions by using uppercase for class names and starting method names with a lowercase letter.

  • Be aware of the "constructor" pattern and the "prototype" chain when using classes for more advanced scenarios.

JavaScript classes provide a clean and structured way to define object constructors and prototypes, making it easier to create and work with objects in your code. They are a fundamental feature of modern JavaScript and are commonly used in various web development projects.

Previous Destructuring
Next Modules