JavaScript Classes
JavaScript classes provide a powerful way to work with objects and inheritance, offering a more structured approach than traditional JavaScript prototypes. In this blog, we will explore what classes are, how they work, and their benefits. You’ll also find sample code snippets to understand how to use them in your projects.
JavaScript classes were introduced in ECMAScript 6 (ES6) to bring a more object-oriented programming (OOP) style to JavaScript. Classes are a blueprint for creating objects with shared properties and methods. They are syntactic sugar over JavaScript’s existing prototype-based inheritance, making it easier to work with objects.
extends
keyword.JavaScript classes provide a cleaner and more readable syntax than traditional object-oriented code in JavaScript. They enable better organization, structure, and code reusability, making it easier to manage large codebases.
Let's start by creating a basic class. Here's an example of a class that represents a "Person."
class Person {
// Constructor method
constructor(name, age) {
this.name = name;
this.age = age;
}
// Method to display information
displayInfo() {
console.log(`${this.name} is ${this.age} years old.`);
}
}
// Creating an instance of the Person class
const person1 = new Person("Alice", 30);
person1.displayInfo(); // Output: Alice is 30 years old.
constructor
is a special method used to initialize the properties name
and age
.displayInfo
method logs the name and age of the person.One of the most powerful features of classes is inheritance. This allows a new class to inherit properties and methods from an existing class. Let's look at how inheritance works in JavaScript.
// Parent class
class Animal {
constructor(name) {
this.name = name;
}
speak() {
console.log(`${this.name} makes a sound.`);
}
}
// Child class inheriting from Animal
class Dog extends Animal {
constructor(name, breed) {
super(name); // Calling the parent class constructor
this.breed = breed;
}
// Overriding the speak method
speak() {
console.log(`${this.name} barks.`);
}
displayBreed() {
console.log(`${this.name} is a ${this.breed}.`);
}
}
const dog1 = new Dog("Max", "Golden Retriever");
dog1.speak(); // Output: Max barks.
dog1.displayBreed(); // Output: Max is a Golden Retriever.
Dog
class extends the Animal
class and inherits the speak
method.super(name)
is used to call the constructor of the parent class (Animal
).speak
method is overridden to provide specific functionality for the Dog
class.JavaScript classes also support getters and setters, which allow you to define special methods to access or modify properties. These are useful for encapsulating data and providing controlled access.
class Car {
constructor(brand, model) {
this.brand = brand;
this.model = model;
}
// Getter method for full car info
get carInfo() {
return `${this.brand} ${this.model}`;
}
// Setter method to update the car model
set updateModel(newModel) {
this.model = newModel;
}
}
const myCar = new Car("Toyota", "Corolla");
console.log(myCar.carInfo); // Output: Toyota Corolla
myCar.updateModel = "Camry"; // Update the model
console.log(myCar.carInfo); // Output: Toyota Camry
carInfo
getter provides a formatted string of the car's brand and model.updateModel
setter allows you to change the model of the car.Static methods are functions that belong to the class itself rather than instances of the class. You can use them to perform operations that are not dependent on individual objects.
class MathOperations {
// Static method
static add(x, y) {
return x + y;
}
static subtract(x, y) {
return x - y;
}
}
console.log(MathOperations.add(5, 3)); // Output: 8
console.log(MathOperations.subtract(5, 3)); // Output: 2
add
and subtract
are called on the class itself rather than on instances of the class.As of ES2022, JavaScript classes support private fields and methods, which allow you to define properties and methods that cannot be accessed outside the class.
class User {
#password; // Private field
constructor(username, password) {
this.username = username;
this.#password = password;
}
// Method to access private field
checkPassword(inputPassword) {
if (this.#password === inputPassword) {
console.log("Password is correct.");
} else {
console.log("Incorrect password.");
}
}
}
const user1 = new User("john_doe", "1234");
user1.checkPassword("1234"); // Output: Password is correct.
#password
field is a private field, and it cannot be accessed directly from outside the class.