JavaScript Classes

JavaScript class is a blueprint for creating objects (a particular data structure), providing initial values for state (member variables or attributes), and implementations of behavior (member functions or methods). In this tutorial, you'll learn the basics of classes in JavaScript.

Creating JavaScript Class

To declare a class in JavaScript, you use the class keyword followed by the class name. The class body is defined within curly braces {}. Here's an example of a simple class:

1class Rectangle { 2 constructor(height, width) { 3 this.height = height; 4 this.width = width; 5 } 6}

Constructor

The constructor is a special method that is called when an object is created from a class. It is used to set the initial values for the object's properties. In this example, the constructor takes two parameters height and width, and sets them as the object's properties using the this keyword.

Creating an Object from a Class

To create an object from a class, you use the new keyword followed by the class name. Here's an example:

1let rect = new Rectangle(10, 20); 2console.log(rect.height); // 10 3console.log(rect.width); // 20

In this example, a new object rect is created from the Rectangle class, and its height and width properties are set to 10 and 20, respectively.

Adding Methods to a Class

In addition to properties, you can also add methods to a class. A method is a function that is associated with an object. Here's an example of adding a method to the Rectangle class:

1class Rectangle { 2 constructor(height, width) { 3 this.height = height; 4 this.width = width; 5 } 6 7 calculateArea() { 8 return this.height * this.width; 9 } 10} 11 12let rect = new Rectangle(10, 20); 13console.log(rect.calculateArea()); // 200

In this example, a new method calculateArea is added to the Rectangle class. This method returns the product of the object's height and width properties.

JavaScript classes provide a way to create objects with properties and methods, and to organize your code in a reusable and maintain