JavaScript classes (introduced in ES6) provide a structured way to create objects with shared properties and methods. They support inheritance, encapsulation, and modularity, making it easier to write object-oriented code.
Syntax
class ClassName {
constructor() {
// Initialize properties here
}
// Define methods here
methodName() {
// Method code
}
}
- The class keyword is used to declare a class.
- The constructor() method is a special method that is automatically called when an instance of the class is created.
- You can define methods inside the class to provide behaviour for objects created from the class.
Key Features of JavaScript Classes
- Encapsulation: Bundles data (properties) and behaviour (methods) together.
- Constructor Method: Initializes properties when an object is created.
- Inheritance: Allows one class to inherit properties and methods from another.
- Code Reusability: Enables the creation of multiple instances with shared functionality.
- Simplicity & Clarity: Provides a clear structure for creating and managing objects.
Creating a Simple Class
A basic class that defines properties and methods. This example shows how to create an object with a constructor and method.
JavaScript class Person { constructor(name, age) { this.name = name; this.age = age; } g() { console.log(`Hello, my name is ${this.name} and I am ${this.age} years old.`); } } let p1 = new Person("Pranjal", 20); p1.g();
OutputHello, my name is Pranjal and I am 20 years old.
- The Person class has a constructor to set name and age, and a g method to log a greeting message.
- An instance (p1) is created with new, passing "Pranjal" and 20, then calls g to print the greeting.
Constructor to Initialize Objects
The constructor is used to initialize the properties of the object when an instance is created.
JavaScript class Car { constructor(make, model, year) { this.make = make; this.model = model; this.year = year; } d() { console.log(`${this.year} ${this.make} ${this.model}`); } } let my = new Car("Toyota", "Corolla", 2021); my.d();
Output2021 Toyota Corolla
- The Car class has a constructor to initialize make, model, and year, and a d method to log the car's details.
- An instance (my) is created with new, passing "Toyota", "Corolla", and 2021, then calls d to print the car's information.
Inheritance in Classes
Inheritance allows one class to extend another, inheriting its properties and methods while adding or overriding functionality.
JavaScript class Car { constructor(make, model, year) { this.make = make; this.model = model; this.year = year; } di() { console.log(`${this.year} ${this.make} ${this.model}`); } } class ElectricCar extends Car { constructor(make, model, year, batteryLife) { super(make, model, year); this.batteryLife = batteryLife; } d() { console.log(`Battery life: ${this.batteryLife} hours`); } } let tesla = new ElectricCar("Tesla", "Model S", 2022, 24); tesla.di() tesla.d();
Output2022 Tesla Model S Battery life: 24 hours
- ElectricCar inherits from Car, using super to set properties and adds batteryLife and d method.
- An instance (tesla) calls both di to display car details and d to show battery life.
Creating Multiple Objects from a Class
Using classes to create multiple objects with the same structure but different data.
JavaScript class Car { constructor(make, model, year) { this.make = make; this.model = model; this.year = year; } d() { console.log(`${this.year} ${this.make} ${this.model}`); } } let c1 = new Car("Toyota", "Corolla", 2021); let c2 = new Car("Honda", "Civic", 2020); c1.d(); c2.d();
Output2021 Toyota Corolla 2020 Honda Civic
- The Car class initializes car details and has a d method to display them.
- Two Car instances (c1 and c2) are created, and d is called on both to show their details.
Advantages of JavaScript Classes
- Improved Code Organization: Classes provide a structured way to organize code, making it easier to understand and maintain.
- Encapsulation: Classes allow bundling data (properties) and methods (functions) that operate on that data in one place, improving code clarity.
- Reusability: Once a class is defined, you can create multiple instances (objects) with similar functionality but different data, promoting reusability.
- Inheritance Support: Classes support inheritance, enabling code reuse and extension, reducing redundancy.
- Easier Debugging and Testing: With a clear object-oriented structure, debugging and testing become easier, as each class is self-contained with its own behavior and properties.
- Scalability: Classes are particularly useful for building large-scale applications by organizing code into manageable units.
Conclusion
JavaScript classes provide a clear and structured way to create and manage objects. With features like constructors, encapsulation, inheritance, and methods, they allow developers to write clean, reusable, and modular code. Whether creating simple objects or building complex hierarchies with inheritance, classes simplify object-oriented programming in JavaScript, making your code more maintainable and scalable.
Similar Reads
Perl | Classes in OOP In this modern world, where the use of programming has moved to its maximum and has its application in each and every work of our lives, we need to adapt ourselves to such programming paradigms that are directly linked to the real-world examples. There has been a drastic change in the competitivenes
6 min read
Understanding Classes and Objects in Java The term Object-Oriented explains the concept of organizing the software as a combination of different types of objects that incorporate both data and behavior. Hence, Object-oriented programming(OOPs) is a programming model, that simplifies software development and maintenance by providing some rul
10 min read
Java - Inner Class vs Sub Class Inner Class In Java, one can define a new class inside any other class. Such classes are known as Inner class. It is a non-static class, hence, it cannot define any static members in itself. Every instance has access to instance members of containing class. It is of three types: Nested Inner ClassMe
3 min read
Java Source File Structure Java source file structure describes that the Java source code file must follow a schema or structure. In this article, we will see some of the important guidelines that a Java program must follow. Â Â Â A Java program has the following structure: Â 1. package statements: A package in Java is a mechani
6 min read
java.lang.reflect.Field Class in Java The ability of the software to analyze itself is known as Reflection. This is provided by the java.lang.reflect package and elements in Class .Field serves the same purpose as the whole reflection mechanism, analyze a software component and describe its capabilities dynamically, at run time rather t
5 min read