JavaScript Classes: Mastering Object-Oriented Programming

Uncover the power of JavaScript classes in this step-by-step guide. Perfect for beginners, this tutorial walks you through object-oriented programming concepts, showing you how to organize and structure your code like a pro
Dev Blogger
JavaScriptImage

Introduction

In this tutorial, we’re diving into JavaScript Classes, which allow you to bring object-oriented programming (OOP) concepts to your JavaScript code.

What You’ll Learn in This Tutorial

  • An introduction to Object-Oriented Programming (OOP)
  • How to create JavaScript Classes
  • How to use constructors, methods, inheritance, and more

Prerequisites

  • This tutorial assumes you already have a basic understanding of:
  • JavaScript syntax
  • Variables and data types


You don’t need advanced knowledge to get started

Getting Started

To keep things organized, we’ll create a simple JavaScript file (app.js) for the code examples, and a basic index.html file to structure our HTML:

  1. Create a basic HTML file (index.html)
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <script src="app.js" defer></script>
  <title>JavaScript Classes Tutorial</title>
</head>
<body>
  <h1>JavaScript Classes Tutorial</h1>
  <div id="output"></div>
</body>
</html>
  1. Create an empty JavaScript file (app.js), where we will write all our class code.

Introduction to Object-Oriented Programming (OOP)

In Object-Oriented Programming (OOP), programs are structured around objects that have properties and behaviors. An object is an instance of a class, and a class is essentially a blueprint for creating objects.

Here’s a simple example:

Step 1: Creating Your First JavaScript Class
Classes are defined using the class keyword. Here’s how we can create a basic class in JavaScript:

// Define a class
class Car {
  constructor(make, model, year) {
    this.make = make;      // Property 1
    this.model = model;    // Property 2
    this.year = year;      // Property 3
  }
displayInfo() {
    return this.year + " " + this.make + " " + this.model;
  }
}

// Create an instance of the class (an object)
const myCar = new Car('Toyota', 'Corolla', 2021);
console.log(myCar.displayInfo()); // Output: "2021 Toyota Corolla"

Explanation:

  • constructor: A special method for creating and initializing an object instance with properties.
  • this: Refers to the current instance of the class.
  • displayInfo(): A method inside the class that outputs information about the car.

Working with Class Methods

Inside a class, you can define methods (functions that perform actions related to the class).

Step 2: Adding More Methods
Let’s add more functionality to our Car class:

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

  displayInfo() {
    return this.year + " " + this.make + " " + this.model;
  }

  startEngine() {
    return "The engine of the " + this.displayInfo() + " is now running!";
  }

  stopEngine() {
    return "The engine of the " + this.displayInfo() + " has been turned off.";
  }
}

const myCar = new Car('Ford', 'Mustang', 2022);
console.log(myCar.startEngine()); // Output: "The engine of the 2022 Ford Mustang is now running!"
console.log(myCar.stopEngine());  // Output: "The engine of the 2022 Ford Mustang has been turned off."

Explanation:

  • Methods like startEngine() and stopEngine() are added to the class to represent actions you can perform on the Car object.

Class Inheritance

Inheritance allows a class to inherit properties and methods from another class. This concept is key to organizing complex code by allowing one class to build upon another.

Step 3: Inheriting a Class
We’ll now create a specialized ElectricCar class that inherits from the Car class:

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

  displayInfo() {
    return this.year + " " + this.make + " " + this.model;
  }

  startEngine() {
    return "The engine of the " + this.displayInfo() + " is now running!";
  }

  stopEngine() {
    return "The engine of the " + this.displayInfo() + " has been turned off.";
  }
}

class ElectricCar extends Car {
  constructor(make, model, year, batteryCapacity) {
    super(make, model, year);  // Call the constructor of the parent class
    this.batteryCapacity = batteryCapacity;  // Additional property for ElectricCar
  }

  chargeBattery() {
    return "Charging the " + this.model + "'s battery. It has a capacity of " + this.batteryCapacity + " kWh.";
  }
}

const myElectricCar = new ElectricCar('Tesla', 'Model S', 2023, 100);
console.log(myElectricCar.displayInfo()); // Output: "2023 Tesla Model S"
console.log(myElectricCar.chargeBattery()); // Output: "Charging the Model S's battery. It has a capacity of 100 kWh."

Explanation:

  • ElectricCar extends Car, which means it inherits all properties and methods from the Car class.
  • The super() function calls the parent class’s constructor to initialize the inherited properties.

Adding Static Methods

Static methods are functions that belong to the class itself, rather than an instance of the class.

Step 4: Implementing Static Methods
Let’s add a static method to the Car class:

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

  static getCarDetails() {
    return "This is a generic car.";
  }

  displayInfo() {
    return this.year + " " + this.make + " " + this.model;
  }
}

console.log(Car.getCarDetails()); // Output: "This is a generic car."

Explanation:

  • static: Defines a method that can be called on the class itself, not instances of it.
  • getCarDetails(): A static method we’ve added that returns a simple message.

Final Output and Testing

Now that you’ve created a class and added several advanced features, it’s time to experiment on your own! Try creating other classes like Bicycle or Truck with similar properties and methods.

Testing is important: Try running this code in different browser consoles or JavaScript environments to see how it behaves in real-time.

Why JavaScript Classes Matter

In JavaScript, classes allow you to create complex, organized programs with reusable objects. By adopting object-oriented programming principles, you can:

  • Keep your code clean and modular.
  • Create reusable blueprints for common structures and behaviors.
  • Make your projects easier to scale and maintain.

These fundamental concepts will serve as the foundation for your future applications.