class
In JavaScript, classes are a template for creating objects. They encapsulate data with code to work on that data. Classes in JavaScript are built on prototypes but also have some syntax and semantics that are not shared with ES5 classalike semantics.
Here's the syntax for classes in JavaScript:
class ClassName {
constructor() {
// constructor is a special method used to create and initialize an object
}
method1() {
// method1 is a function within a class
}
method2() {
// method2 is another function within a class
}
}
The constructor method is a special method for creating and initializing an object created with a class. There can only be one special method with the name "constructor" in a class.
Here's an example of how to define a class and create an object using that class:
// Define a class
class Rectangle {
// The constructor initializes the properties
constructor(height, width) {
this.height = height;
this.width = width;
}
// Method to return the area
area() {
return this.height * this.width;
}
// Method to return the perimeter
perimeter() {
return 2 * (this.height + this.width);
}
}
// Create an instance of the class
const myRectangle = new Rectangle(10, 20);
console.log(myRectangle.area()); // Outputs: 200
console.log(myRectangle.perimeter()); // Outputs: 60
In this example, Rectangle is a class and myRectangle is an object (an instance of Rectangle). The new keyword is used to create an instance of the class, which means a new object is created from the class, and the constructor of the class is called automatically.
Classes support inheritance, meaning you can create a new class that inherits properties and methods from another class. This is done using the extends keyword.
class Square extends Rectangle {
constructor(sideLength) {
super(sideLength, sideLength);
}
}
const mySquare = new Square(10);
console.log(mySquare.area()); // Outputs: 100
console.log(mySquare.perimeter()); // Outputs: 40
In this code, Square is a new class that inherits from Rectangle. The super keyword is used to call the constructor of the superclass. The mySquare object is an instance of the Square class, and it can use the area and perimeter methods defined in Rectangle.