
JavaScript Class
In JavaScript, a class is a template or blueprint for creating objects. It defines the properties and methods that an object of that class will have. Here’s an example of how to create a class in JavaScript:
class Car {
constructor(make, model, year) {
this.make = make;
this.model = model;
this.year = year;
}
startEngine() {
console.log("Engine started!");
}
stopEngine() {
console.log("Engine stopped!");
}
drive() {
console.log("Driving...");
}
}
// Create an instance of the Car class
const myCar = new Car("Toyota", "Camry", 2022);
// Accessing properties and methods of the instance
console.log(myCar.make); // Output: "Toyota"
console.log(myCar.model); // Output: "Camry"
console.log(myCar.year); // Output: 2022
myCar.startEngine(); // Output: "Engine started!"
myCar.drive(); // Output: "Driving..."
myCar.stopEngine(); // Output: "Engine stopped!"
In the example above, we define a Car
class using the class
keyword. The constructor
method is a special method that is called when a new object is created from the class. It initializes the properties of the object (make
, model
, year
) based on the arguments passed to the constructor.
The class also has additional methods (startEngine
, stopEngine
, drive
) that define the behavior of a car object.
To create an instance of the Car
class, we use the new
keyword followed by the class name and provide the necessary arguments to the constructor.
We can then access the properties and call the methods of the instance using dot notation (myCar.make
, myCar.startEngine()
, etc.).
Classes in JavaScript follow the object-oriented programming paradigm and provide a way to organize and structure code by encapsulating related data and behavior into reusable objects.