Source: How to create class in JavaScript
For more questions and answers visit our website at Frontend Interview Questions
In JavaScript, you can define a class using the `class` keyword. Here’s the basic syntax to define a class in JavaScript:
class ClassName {
// Class properties
// Constructor
constructor() {
// Initialize properties
}
// Methods
methodName() {
// Method logic
}
}
Let’s break down the syntax:
— `class ClassName` declares a new class with the name “ClassName”. You can replace “ClassName” with the desired name for your class.
— The class body is wrapped in curly braces `{}` and contains the properties and methods of the class.
— The `constructor` method is a special method that is executed when an instance of the class is created. It is used to initialize the class properties. You can define the constructor using the `constructor` keyword followed by parentheses `()`.
— Inside the class body, you can define other methods that perform specific actions or computations. Methods are defined without the `function` keyword.
Here’s an example of defining a simple class in JavaScript:
class Person {
constructor(name, age)…