How to Create JavaScript Classes


JavaScript classes are a way to create reusable object blueprints. Classes allow you to define the structure and behavior of objects, making your code more organized and easier to maintain. In this guide, we'll explore how to create JavaScript classes and provide examples to illustrate their usage.


Defining a JavaScript Class


To create a JavaScript class, you can use the class keyword, followed by the class name. Within the class, you can define properties and methods:


class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
greet() {
console.log(`Hello, my name is ${this.name} and I'm ${this.age} years old.`);
}
}

In this example, we've defined a Person class with a constructor and a greet method. The constructor initializes the object's properties, and the greet method logs a greeting.


Creating Instances of a Class


Once a class is defined, you can create instances (objects) of that class using the new keyword:


const person1 = new Person("Alice", 30);
const person2 = new Person("Bob", 25);
person1.greet(); // Outputs: "Hello, my name is Alice and I'm 30 years old."
person2.greet(); // Outputs: "Hello, my name is Bob and I'm 25 years old."

We've created two Person objects, person1 and person2, with different values for the name and age properties. Then, we called the greet method on each object to display a personalized greeting.


Class Inheritance


JavaScript supports class inheritance, allowing you to create a subclass (child class) that inherits properties and methods from a parent class (superclass). You can use the extends keyword to define a subclass:


class Student extends Person {
constructor(name, age, grade) {
super(name, age); // Call the constructor of the parent class
this.grade = grade;
}
study() {
console.log(`${this.name} is studying in grade ${this.grade}.`);
}
}
const student = new Student("Eve", 15, 9);
student.greet(); // Outputs: "Hello, my name is Eve and I'm 15 years old."
student.study(); // Outputs: "Eve is studying in grade 9."

In this example, the Student class extends the Person class. It calls the parent class constructor using super() and introduces its own property and method. An instance of Student inherits the properties and methods from both classes.


Conclusion


JavaScript classes provide a structured way to create and manage objects in your code. With classes, you can define the blueprint of objects and create instances with consistent properties and behavior. Understanding class inheritance further empowers you to build complex hierarchies of objects in your applications.


Happy coding with JavaScript classes!