In JavaScript, a class is a type of function. Classes are declared with the class keyword.
Checkout this video:
Introduction
Classes in JavaScript are blueprints for creating objects. They are a template for creating objects with specific characteristics.
A class is a template for an object, and you can use it to create multiple objects. Each object that you create from a class is called an instance of that class.
You can use classes to define properties and methods for objects. A property is a value that you can storesomething in, and a method is something that you can do with an object.
What is a Class?
In JavaScript, a class is a type of function. Classes are declared with the class keyword:
class Rectangle {
constructor(height, width) {
this.height = height;
this.width = width;
}
}
The above example creates a new class called Rectangle. A class declaration creates a new function, with an implicitprototype property whose value is an object containing properties and methods that should be shared by all instances of the class.
Creating a Class
A class is a type of function, but instead of using the keyword function to initiate it, we use the keyword class, and the properties are declared inside a constructor() method.
class Car {
constructor(manufacturer, model) {
this.manufacturer = manufacturer;
this.model = model;
}
drive() {
console.log(‘vroom’);
}
}
const bmw = new Car(‘BMW’, ‘X5’);
Class Inheritance
Inheritance is implemented via the “extends” keyword:
class Person {
constructor(name) {
this.name = name;
}
sayHello() {
return `Hello, my name is ${this.name}`;
}
}
Conclusion
In conclusion, a class is a code template for creating objects. Classes are a relatively new feature in JavaScript, introduced in 2015 with the release of ES6. Classes provide a way to group together related data and functionality, which can be used to create objects. Objects created from a class are called “instances.” Classes can have constructors, which are functions that run when an instance of the class is created. Classes can also have methods, which are functions that can be run on instances of the class.