Enhancing Skills

The Power of Classes in JavaScript Programming

Classes are a fundamental part of modern JavaScript and are widely used in many programming languages. They provide a way to create and manage objects, enabling developers to structure and organize code efficiently. Understanding how classes work can unlock new levels of creativity and productivity in your coding projects. This article will explain the power of classes, their benefits, and how they can be used effectively in JavaScript.


A class is a blueprint for creating objects. It defines properties and behaviors that the objects created from the class will have, making your code easier to manage and reuse. Here are some of the key advantages of using classes in JavaScript:

Organization and Maintainability:

Classes make it easier to organize code by logically grouping related properties and methods together. This makes the code more readable and easier to maintain.

class Person {
  constructor(name, age) {
    this.name = name;
    this.age = age;
  }

  introduce() {
    console.log(`Hi, I'm ${this.name} and I'm ${this.age} years old.`);
  }
}

const john = new Person("John", 30);
john.introduce();  // Output: Hi, I'm John and I'm 30 years old.
  1. Class Definition (class Person):
    • The Person class is defined as a blueprint for creating person objects. It has a constructor to initialize properties (name and age) and a method introduce() to display an introduction message.
  2. Constructor (constructor(name, age)):
    • The constructor method is a special method called when a new object is created from the class.
    • It takes two parameters: name (a string representing the person’s name) and age (a numeric value representing the person’s age).
    • The this keyword is used to assign the values passed to the constructor to the instance properties name and age.
  3. introduce() Method:
    • This is a public method that can be called on any object created from the Person class.
    • It logs a message to the console introducing the person by their name and age.
    • The template literal (${}) is used to dynamically insert the values of name and age into the output string.
  4. Creating an Object (const john = new Person("John", 30)):
    • A new object, john, is created from the Person class using the new keyword.
    • The constructor is called with the arguments "John" and 30, initializing the name property to "John" and the age property to 30.
  5. Calling the Method (john.introduce()):
    • The introduce method is called on the john object.
    • It outputs: "Hi, I'm John and I'm 30 years old." to the console.
What This Code Achieves:

The code defines a Person class with properties (name and age) and a method (introduce()) to display an introduction message. This allows you to create and interact with Person objects, encapsulating the properties and behaviors related to a person in a structured way.

Encapsulation:

Classes help group related data and functions together, hiding the internal details and exposing only what is necessary.

class Car {
  #brand;  // Private field
  #speed;  // Private field

  constructor(brand, speed) {
    this.#brand = brand;
    this.#speed = speed;
  }

  accelerate() {
    this.#speed += 10;
    console.log(`${this.#brand} accelerates to ${this.#speed} km/h.`);
  }
}

const myCar = new Car("Toyota", 100);
myCar.accelerate();  // Output: Toyota accelerates to 110 km/h.

Class Definition (class Car): The Car class is defined, which serves as a blueprint for creating car objects. This class has two private fields (#brand and #speed), a constructor method, and an accelerate method.

Private Fields (#brand and #speed):

  • #brand and #speed are private fields. They are defined using the # symbol, which makes them private to the class.
  • Private fields cannot be accessed directly from outside the class, ensuring the internal details of the class are hidden.

Constructor (constructor(brand, speed)):

  • The constructor method is a special method used to create and initialize objects of the class.
  • It takes two parameters (brand and speed) and assigns them to the private fields (#brand and #speed).
  • When a new object is created from the class, the constructor is automatically called to set up the object’s initial state.

accelerate() Method:

  • This is a public method that can be called on any object created from the Car class.
  • It increases the private #speed field by 10 each time it is called.
  • It then logs a message to the console that shows the car’s brand and its new speed.

Creating an Object (const myCar = new Car("Toyota", 100)):

  • A new object, myCar, is created from the Car class using the new keyword.
  • The constructor is called with the arguments "Toyota" and 100, initializing #brand to "Toyota" and #speed to 100.

Calling the Method (myCar.accelerate()):

  • The accelerate method is called on the myCar object.
  • The method increases the speed by 10, changing #speed from 100 to 110.
  • It outputs: "Toyota accelerates to 110 km/h." to the console.
What This Code Achieves:

The code defines a Car class with a private brand and speed, initializes these values when a new car is created, and provides a method (accelerate) to increase the car’s speed while keeping internal fields protected. The result is a flexible and secure way to handle car objects with their properties encapsulated.

Inheritance (and Reusability):

Classes can be reused to create multiple objects with similar properties and methods. They also allow for inheritance, where a new class can extend an existing class, gaining its properties and methods.

class Vehicle {
  constructor(type, speed) {
    this.type = type;
    this.speed = speed;
  }

  move() {
    console.log(`${this.type} is moving at ${this.speed} km/h.`);
  }
}

class Bike extends Vehicle {  // Inherits from Vehicle
  ringBell() {
    console.log("Ring ring!");
  }
}

const myBike = new Bike("Bike", 20);
myBike.move();    // Output: Bike is moving at 20 km/h.
myBike.ringBell();  // Output: Ring ring!
  1. Class Definition (class Vehicle):
    • The Vehicle class is defined as a blueprint for creating vehicle objects. It has a constructor to initialize properties (type and speed) and a method move() to display information about the vehicle’s movement.
  2. Constructor (constructor(type, speed)):
    • The constructor method is a special method called when a new object is created from the class.
    • It takes two parameters: type (like “Bike”, “Car”, etc.) and speed (numeric value representing the vehicle’s speed).
    • The this keyword is used to assign the values passed to the constructor to the instance properties type and speed.
  3. move() Method:
    • This public method is defined to log a message about the vehicle’s type and speed to the console.
    • It uses the properties type and speed from the class instance to create a dynamic message.
  4. Inheritance (class Bike extends Vehicle):
    • The Bike class is created by extending the Vehicle class, meaning it inherits all the properties and methods of Vehicle.
    • This allows the Bike class to use the constructor and move methods of the Vehicle class.
  5. ringBell() Method:
    • A new method specific to the Bike class, ringBell(), is added to provide additional functionality unique to the Bike class.
    • It logs “Ring ring!” to the console, simulating the ringing of a bicycle bell.
  6. Creating an Object (const myBike = new Bike("Bike", 20)):
    • A new object myBike is created from the Bike class using the new keyword.
    • The constructor of the parent Vehicle class is called with the arguments "Bike" and 20, initializing the type to "Bike" and speed to 20.
  7. Calling Methods (myBike.move() and myBike.ringBell()):
    • myBike.move() calls the inherited move method from the Vehicle class, outputting: "Bike is moving at 20 km/h.".
    • myBike.ringBell() calls the ringBell method specific to the Bike class, outputting: "Ring ring!".
What This Code Achieves:

The code demonstrates how classes can inherit properties and methods from other classes using JavaScript’s extends keyword. The Bike class inherits the common behavior of Vehicle (moving with a speed) while adding its unique behavior (ringing a bell). This approach promotes code reuse, organization, and easy maintenance by leveraging object-oriented programming principles like inheritance.

Polymorphism:

Classes enable polymorphism, allowing methods to be overridden and objects to be treated as instances of their parent class while behaving differently.

class Animal {
  speak() {
    console.log("Some generic animal sound.");
  }
}

class Dog extends Animal {
  speak() {
    console.log("Woof!");
  }
}

class Cat extends Animal {
  speak() {
    console.log("Meow!");
  }
}

function makeAnimalSpeak(animal) {
  animal.speak();
}

const dog = new Dog();
const cat = new Cat();

makeAnimalSpeak(dog);  // Output: Woof!
makeAnimalSpeak(cat);  // Output: Meow!
  1. Class Definition (class Animal):
    • The Animal class is defined as a base class with a speak() method that outputs a generic animal sound: "Some generic animal sound.".
    • This class serves as a parent class, providing a common interface (the speak method) for other classes to use or override.
  2. speak() Method in Animal Class:
    • The speak() method in the Animal class logs a generic message to the console.
    • This method is meant to be overridden by subclasses that provide specific animal sounds.
  3. Inheritance (class Dog extends Animal and class Cat extends Animal):
    • The Dog and Cat classes are created by extending the Animal class, meaning they inherit all properties and methods from Animal.
    • Both classes override the speak() method to provide specific sounds for each animal:
      • The Dog class’s speak() method logs "Woof!" to the console.
      • The Cat class’s speak() method logs "Meow!" to the console.
  4. makeAnimalSpeak() Function:
    • This function accepts an object (animal) as a parameter and calls its speak() method.
    • Because Dog and Cat are both subclasses of Animal, they can be passed to this function, and their overridden speak methods will be called.
  5. Creating Objects (const dog = new Dog(); const cat = new Cat();):
    • Two objects are created:
      • dog is an instance of the Dog class.
      • cat is an instance of the Cat class.
    • Both objects inherit from Animal but have their unique implementations of the speak() method.
  6. Calling the Function (makeAnimalSpeak(dog) and makeAnimalSpeak(cat)):
    • makeAnimalSpeak(dog) calls the speak() method on the Dog instance, which outputs "Woof!".
    • makeAnimalSpeak(cat) calls the speak() method on the Cat instance, which outputs "Meow!".
What This Code Achieves:

This code demonstrates the concept of polymorphism in object-oriented programming.

  • Polymorphism allows different classes (Dog and Cat) to be treated as instances of their parent class (Animal) while still having different behaviors (different outputs for the speak() method).
  • It shows how a single function (makeAnimalSpeak) can operate on different types of objects that share a common interface, providing flexibility and extensibility in code.

Classes in JavaScript provide a powerful way to create and manage objects. They offer encapsulation, reusability, inheritance, and polymorphism, making code more organized, efficient, and easy to maintain. By leveraging the power of classes, developers can write cleaner and more scalable applications.

Feel like you jumped into the middle of this learning series, to catch-up, please read: Learning Game Development: Complete guide using HTML5, CSS & JavaScript.


Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.