JavaScript Classes

What Are JavaScript Classes?

A class in JavaScript is a blueprint for creating objects. It encapsulates data (properties) and behaviors (methods) into a single entity. Classes bring OOP concepts like inheritance, encapsulation, and abstraction into JavaScript.

Defining a Class

You can define a class using the class keyword.

Syntax:

class ClassName {
constructor(parameters) {
// Initialize properties
}
// Define methods
}

Example 1: Basic Class Definition

class Car {
constructor(brand, model) {
this.brand = brand;
this.model = model;
}

// Method
displayInfo() {
console.log(`This car is a ${this.brand} ${this.model}.`);
}
}

// Creating an object
const myCar = new Car("Toyota", "Corolla");
myCar.displayInfo(); // Output: This car is a Toyota Corolla.

Components of a JavaScript Class

1) Constructor Method:

The constructor method initializes the properties of a class. It is automatically called when a new object is created.

Example:

class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
}
const person1 = new Person("Alice", 25);
console.log(person1.name); // Output: Alice

2) Methods:

Functions inside a class are called methods.

Example:

class Animal {
constructor(type) {
this.type = type;
}

speak() {
console.log(`${this.type} makes a sound.`);
}
}

const dog = new Animal("Dog");
dog.speak(); // Output: Dog makes a sound.

3) Static Methods:

Static methods belong to the class itself, not to any instance. Use the static keyword to define them.

Example:

class MathOperations {
static add(a, b) {
return a + b;
}
}

console.log(MathOperations.add(5, 3)); // Output: 8

Inheritance in Classes

JavaScript classes support inheritance, allowing you to create new classes based on existing ones. Use the extends keyword for inheritance and the super keyword to call the parent class’s constructor or methods.

Example:

class Animal {
constructor(name) {
this.name = name;
}

eat() {
console.log(`${this.name} is eating.`);
}
}

class Dog extends Animal {
bark() {
console.log(`${this.name} is barking.`);
}
}

const myDog = new Dog("Rex");
myDog.eat(); // Output: Rex is eating.
myDog.bark(); // Output: Rex is barking.

Getters and Setters

You can use getters and setters to control access to class properties.

Example:

class Rectangle {
constructor(width, height) {
this.width = width;
this.height = height;
}

get area() {
return this.width * this.height;
}

set updateWidth(newWidth) {
this.width = newWidth;
}
}

const rect = new Rectangle(10, 20);
console.log(rect.area); // Output: 200
rect.updateWidth = 15;
console.log(rect.area); // Output: 300

Private Fields and Methods

JavaScript classes support private fields and methods, which are denoted by a #. Private members cannot be accessed outside the class.

Example:

class BankAccount {
#balance = 0;

deposit(amount) {
this.#balance += amount;
}

getBalance() {
return this.#balance;
}
}

const account = new BankAccount();
account.deposit(1000);
console.log(account.getBalance()); // Output: 1000

Key Benefits of Using Classes

  1. Improved Code Readability:
    Classes provide a cleaner and more intuitive structure for defining objects and their behavior.
  2. Reusability Through Inheritance:
    Classes make it easy to reuse code by inheriting properties and methods.
  3. Encapsulation:
    By bundling data and methods, classes ensure better modularity and code maintenance.
  4. OOP Principles:
    Classes make it easier to implement object-oriented principles in JavaScript.

Advanced Class Concepts

1) Abstract Classes:

While JavaScript does not directly support abstract classes, you can simulate them by throwing an error if a method is not implemented.

Example:

class AbstractShape {
constructor() {
if (new.target === AbstractShape) {
throw new Error("Cannot instantiate abstract class.");
}
}

draw() {
throw new Error("Method 'draw()' must be implemented.");
}
}

class Circle extends AbstractShape {
draw() {
console.log("Drawing a circle.");
}
}

const circle = new Circle();
circle.draw(); // Output: Drawing a circle.

2) Polymorphism:

Using inheritance, you can override parent methods in child classes.

Example:

class Animal {
speak() {
console.log("Animal is speaking.");
}
}

class Cat extends Animal {
speak() {
console.log("Cat is meowing.");
}
}

const myCat = new Cat();
myCat.speak(); // Output: Cat is meowing.

Common Mistakes with Classes

  1. Forgetting to use the new keyword when creating objects.
  2. Trying to call private methods or access private fields directly.
  3. Overriding methods without using super.

Leave a Comment