In JavaScript, classes are defined using the class keyword. Inside the class, we define a constructor method that initializes the properties when an object is created.

Syntax:

JavaScript
class ClassName {
  constructor(parameters) {
    // Initialize properties
  }
  
  // Define methods
}

Example: Car Class

Consider a real-world example of a Car class. Each car has properties like make, model, and year and methods like start and stop.

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

  start() {
    console.log(`${this.make} ${this.model} is starting...`);
  }

  stop() {
    console.log(`${this.make} ${this.model} has stopped.`);
  }
}

// Creating an object (instance) of Car
const myCar = new Car("Toyota", "Camry", 2021);
myCar.start();  // Output: Toyota Camry is starting...
myCar.stop();   // Output: Toyota Camry has stopped.

In this example:

  • The Car class has a constructor to initialize make, model, and year properties.
  • start and stop methods define actions for a car.
  • myCar is an instance of Car, representing a specific car with the given properties and behavior.