JavaScript Classes
JavaScript classes are a way to define objects and their behavior using a syntax that is similar to class-based object-oriented programming languages like Java or Python.
Introduced in ECMAScript 2015 (ES6), JavaScript classes provide a more intuitive and structured syntax for creating constructor functions and prototypes.
Example
class Rectangle { constructor(width, height) { this.width = width; this.height = height; } // Method to calculate the area calculateArea() { return this.width * this.height; } } // Creating an instance of Rectangle const rectangle = new Rectangle(5, 3); // Calling a method on the instance console.log(rectangle.calculateArea()); // Output: 15
JavaScript classes support inheritance, allowing you to create subclasses with their own constructors and methods that can inherit properties and methods from a parent class.
Here's a simple example of inheritance:
Example
class Square extends Rectangle { constructor(sideLength) { // Call the parent class constructor with super super(sideLength, sideLength); } } // Creating an instance of Square const square = new Square(4); // Calling a method on the instance console.log(square.calculateArea()); // Output: 16
The Constructor Method
In JavaScript classes, the constructor method is a special method that is automatically called when a new instance of the class is created using the new keyword. It's used to initialize the object's properties or perform any setup that is necessary before the object is ready for use.
Example
class MyClass { constructor(parameter1, parameter2, ...) { // Initialize properties or perform setup this.property1 = parameter1; this.property2 = parameter2; // ... } }
Class Methods
In JavaScript classes, methods are functions defined within the class that can be called on instances of that class.
Example
class Rectangle { constructor(width, height) { this.width = width; this.height = height; } // Instance method to calculate the area calculateArea() { return this.width * this.height; } // Static method to create a square static createSquare(sideLength) { return new Rectangle(sideLength, sideLength); } } // Creating an instance of Rectangle const rectangle = new Rectangle(5, 3); // Calling the instance method console.log(rectangle.calculateArea()); // Output: 15 // Calling the static method const square = Rectangle.createSquare(4); console.log(square.calculateArea()); // Output: 16You can click on above box to edit the code and run again.