Classes
In JavaScript, classes provide a way to define blueprints for creating objects. They allow you to encapsulate data and behavior into a single entity. Classes are a key concept in object-oriented programming (OOP) and are widely used in JavaScript for building web applications.
Creating a Class
To create a class in JavaScript, you can use the class keyword followed by the class name. Here's an example of a Rectangle class that represents a rectangle shape:
1class Rectangle {
2 constructor(width, height) {
3 this.width = width;
4 this.height = height;
5 }
6
7 calculateArea() {
8 return this.width * this.height;
9 }
10}In this example, we define a Rectangle class with a constructor method that takes in width and height parameters. The constructor method is used to initialize the object's properties.
Creating Objects from a Class
Once a class is defined, you can create objects from it using the new keyword. Here's an example of creating a Rectangle object:
1const rectangle = new Rectangle(5, 7);
2console.log(rectangle); // Output: Rectangle { width: 5, height: 7 }In this example, we create a rectangle object with a width of 5 and height of 7.
Accessing Methods
Objects created from a class can access the class methods using dot notation. Here's an example of calling the calculateArea method for the rectangle object:
1console.log(rectangle.calculateArea()); // Output: 35In this example, we call the calculateArea method on the rectangle object and it returns the calculated area of the rectangle.
Classes in JavaScript provide a powerful way to organize and structure your code. They allow you to create objects with properties and methods, making your code more modular and reusable.
xxxxxxxxxxclass Rectangle { constructor(width, height) { this.width = width; this.height = height; } calculateArea() { return this.width * this.height; }}const rectangle = new Rectangle(5, 7);console.log(rectangle.calculateArea()); // Output: 35

