In JavaScript, classes were introduced with ECMAScript 6 (ES6) to provide a more convenient and structured way to create and work with objects.
Classes in JavaScript are syntactical sugar over the existing prototype-based inheritance and constructor functions.
They allow us to define a blueprint for creating objects with methods and properties.
To declare a class, we use the "class" keyword followed by the name of the class.
The class may contain a constructor method for initializing object instances, as well as other methods and properties.
class Person { constructor(name, age) { this.name = name; this.age = age; } greet() { console.log(`Hello, my name is ${this.name} and I am ${this.age} years old.`); } }
We can create instances of a class using the new keyword.
const person1 = new Person("Alice", 33); const person2 = new Person("Sarah", 22); person1.greet(); // Outputs: Hello, my name is Alice and I am 33 years old. person2.greet(); // Outputs: Hello, my name is Sarah and I am 22 years old.
class MathOperations { static multiply(x, y) { return x * y; } static divide(x, y) { return x / y; } } console.log(MathOperations.multiply(10, 2)); // Outputs: 20 console.log(MathOperations.divide(8, 2)); // Outputs: 4
We can define static methods that are called on the class itself rather than on instances of the class.
class Square { public _side; constructor(side) { this._side = side; } get side() { return this._side; } set side(newSide) { if (newSide > 0) { this._side = newSide; } else { console.error("Side must be greater than 0."); } } get area() { return this._side * this._side; } } const yourSquare = new Square(10); console.log(yourSquare.side); // Outputs: 10 console.log(yourSquare.area); // Outputs: 100 yourSquare.side = 4; console.log(yourSquare.side); // Outputs: 4 console.log(yourSquare.area); // Outputs: 16 yourSquare.side = -2; // Error: Side must be greater than 0.
We can use getter and setter methods to control access to the properties of an object.
Classes provide a cleaner syntax for object-oriented programming in JavaScript and make it easier to work with object creation and inheritance.
They are widely used in modern JavaScript development.