A Comprehensive Guide to JavaScript Classes

Welcome, JavaScript adventurers! In this chapter, we embark on a journey into the realm of object-oriented programming (OOP) using JavaScript classes. Classes provide a structured way to create objects with shared properties and behaviors, fostering code reusability and maintainability. Buckle up as we explore the fundamentals, practical applications, and advanced techniques of JavaScript classes.

The Essence of Classes: Blueprints for Objects

  • Classes act as templates or blueprints for creating objects. They define the properties (data) and methods (functions) that objects of that class will share.
  • Just like creating a blueprint for a house, a class defines the structure for objects, but the actual objects (instances) are created from the class.

Creating and Using Classes: The Basic Syntax

				
					class Car {
  // Class properties (using the constructor)
  constructor(model, year) {
    this.model = model;
    this.year = year;
  }

  // Class methods (functions)
  greet() {
    console.log("Hello from your", this.year, this.model + "!");
  }
}

// Creating object instances (instances of the Car class)
const car1 = new Car("Honda Civic", 2023);
const car2 = new Car("Toyota Camry", 2022);

car1.greet(); // Output: Hello from your 2023 Honda Civic!
car2.greet(); // Output: Hello from your 2022 Toyota Camry!

				
			

Explanation:

  • The Car class defines two properties (model and year) using the constructor method. The constructor is a special method that gets called whenever a new object (instance) is created from the class.
  • The greet method is a function defined within the class to log a greeting message.
  • We use the new keyword to create instances (car1 and car2) of the Car class, providing arguments for the constructor (model and year).
  • When we call car1.greet() and car2.greet(), the greet method is invoked on each object instance, printing the personalized greeting messages.

Class Inheritance: Building Upon Existing Classes

Inheritance allows us to create new classes (subclasses) that inherit properties and methods from an existing class (superclass). This promotes code reusability and reduces redundancy

				
					class ElectricCar extends Car {
  constructor(model, year, batteryRange) {
    super(model, year); // Call the superclass constructor
    this.batteryRange = batteryRange;
  }

  greet() {
    super.greet(); // Call the superclass greet method
    console.log("...with a range of", this.batteryRange, "miles!");
  }
}

const electricCar = new ElectricCar("Tesla Model S", 2024, 350);
electricCar.greet(); // Output: Hello from your 2024 Tesla Model S! ...with a range of 350 miles!

				
			

Explanation:

  • The ElectricCar class inherits from the Car class using the extends keyword.
  • The ElectricCar constructor calls the superclass (Car) constructor using super(model, year) to initialize the inherited properties.
  • The greet method in ElectricCar overrides the superclass method. It first calls the superclass greet using super.greet() to print the base greeting, then adds its own message about the battery range.
  • We create an electricCar instance, and its greet method demonstrates the inheritance hierarchy.

Class Properties (Public, Private, and Static): Defining Accessibility

  • Class properties can have different access levels:
    • Public: Accessible from anywhere (outside and inside the class).
    • Private: Accessible only from inside the class (using this).
    • Static: Shared across all instances of the class (accessed using the class name, not the object instance).
				
					class Person {
  #name; // Private property (using # symbol)
  constructor(name) {
    this.#name = name;
  }

  getName() { // Public method to access private property
    return this.#name;
  }

  static greetAll() {
    console.log("Hello from everyone!");
  }
}

const person1 = new Person("Alice");
console.log(person1.getName()); // Output: Alice (public method accesses private property)

				
			

Explanation:

  • We use the # symbol to define a private property (#name). Private properties are only accessible from within the class using this.
  • The getName method provides a public way to access the private #name property.
  • static methods are defined using the static keyword. They are associated with the class itself, not the object instances. We can call them using the class name directly (e.g., Person.greetAll()).

Advanced Topics: Getters, Setters, and Class Expressions

Getters and Setters: These are special methods that allow us to control how properties are accessed and modified.

  • Getters: Functions that are executed when a property is accessed (like reading a value).
  • Setters: Functions that are executed when a property is assigned a new value
				
					class Circle {
  constructor(radius) {
    this._radius = radius; // Private property with underscore prefix (convention)
  }

  get area() { // Getter for the calculated area
    return Math.PI * this._radius * this._radius;
  }

  set radius(value) { // Setter to validate and assign radius
    if (value <= 0) {
      throw new Error("Radius cannot be negative or zero!");
    }
    this._radius = value;
  }
}

const circle = new Circle(5);
console.log(circle.area); // Output: 78.53981633974483 (getter is called)

circle.radius = -10; // Throws an error (setter validates input)

				
			

Explanation:

  • We use a private property (_radius) with an underscore prefix (a convention for private properties in JavaScript).
  • The area getter calculates and returns the circle’s area using the private _radius.
  • The radius setter validates the input value before assigning it to the private property. It throws an error if the radius is negative or zero.
  • Class Expressions: Similar to function expressions, class expressions allow you to define classes dynamically by assigning them to variables.
				
					const Point = class {
  constructor(x, y) {
    this.x = x;
    this.y = y;
  }

  toString() {
    return `Point(${this.x}, ${this.y})`;
  }
};

const point = new Point(3, 4);
console.log(point.toString()); // Output: Point(3, 4)

				
			

Explanation:

  • We define a class expression using const Point = class { ... }.
  • This allows for more dynamic class creation, potentially based on user input or other conditions.

By understanding classes, inheritance, property access levels, and advanced features like getters, setters, and class expressions, you gain the power to structure your JavaScript code effectively. Classes promote code reusability, maintainability, and readability, making your applications more organized and easier to manage as they grow in complexity. Happy coding !❤️

Table of Contents

Contact here

Copyright © 2025 Diginode

Made with ❤️ in India