Creating a Class in JavaScript

JavaScript is a versatile programming language that supports object-oriented programming (OOP). One of the fundamental concepts in OOP is the class, which serves as a blueprint for creating objects. In this article, we will explore how to create a class in JavaScript, understand its structure, and learn about various features such as inheritance, encapsulation, and static methods.

What is a Class?

A class is a template or a blueprint for creating objects. It defines the properties (data) and methods (functions) that the objects of that class will have. In simpler terms, a class is like a cookie cutter, and the objects are the cookies created using that cutter.

Syntax of a Class

Here’s the basic syntax for creating a class in JavaScript:

// Define a class using the 'class' keyword
class ClassName {
  // Constructor method
  constructor() {
    // Initialize properties here
  }

  // Methods
  method1() {
    // Code here
  }

  method2() {
    // Code here
  }
}

Example: Creating a Simple Class

Let’s create a simple class called Person that has a constructor method and a greeting method.

// Define the Person class
class Person {
  // Constructor method with parameters
  constructor(firstName, lastName) {
    this.firstName = firstName;
    this.lastName = lastName;
  }

  // Method to return a greeting
  greeting() {
    return `Hello, my name is ${this.firstName} ${this.lastName}`;
  }
}

// Create an instance of the Person class
const person1 = new Person('John', 'Doe');

// Call the greeting method
console.log(person1.greeting()); // Output: Hello, my name is John Doe

Explanation

  • class Keyword: We use the class keyword to define a class.
  • Constructor Method: The constructor() method is a special method used to initialize the properties of the class when an object is created.
  • Properties: These are defined inside the constructor method using this.propertyName = value;.
  • Methods: These are functions that define the behavior of the objects created from the class.
  • Creating an Instance: We use the new keyword followed by the class name to create an instance (object) of the class.

Inheritance in Classes

Inheritance is a key feature of OOP where a class (called a subclass) can inherit properties and methods from another class (called a superclass). This promotes code reuse and creates a hierarchical relationship between classes.

Syntax of Inheritance

// Subclass extending a superclass
class SubClassName extends SuperClassName {
  // Constructor method
  constructor() {
    // Call the superclass constructor
    super();
  }

  // Methods
}

Example: Inheritance in JavaScript

Let’s create a Student class that inherits from the Person class.

// Define the Student class extending Person
class Student extends Person {
  // Constructor method with additional parameter
  constructor(firstName, lastName, studentID) {
    // Call the superclass constructor
    super(firstName, lastName);

    // Additional property
    this.studentID = studentID;
  }

  // Method to display student ID
  displayStudentID() {
    return `My student ID is ${this.studentID}`;
  }
}

// Create an instance of the Student class
const student1 = new Student('Jane', 'Smith', '12345');

// Call methods inherited from Person and Student
console.log(student1.greeting()); // Output: Hello, my name is Jane Smith
console.log(student1.displayStudentID()); // Output: My student ID is 12345

Explanation

  • extends Keyword: We use the extends keyword to create a subclass that inherits from a superclass.
  • super() Keyword: Inside the subclass constructor, we use super() to call the constructor of the superclass and initialize its properties.
  • Inherited Methods: The subclass inherits all the methods of the superclass and can also have its own additional methods.

Encapsulation

Encapsulation is the practice of hiding the internal details of an object and exposing only the necessary parts to the outside world. In JavaScript, encapsulation can be achieved using private methods and properties.

Private Methods and Properties

In JavaScript, private methods and properties are denoted by a # symbol before the name.

Example: Encapsulation in JavaScript

// Define a BankAccount class with private properties
class BankAccount {
  #balance; // Private property

  constructor(accountNumber, initialBalance) {
    this.accountNumber = accountNumber;
    this.#balance = initialBalance;
  }

  // Public method to deposit money
  deposit(amount) {
    this.#balance += amount;
  }

  // Public method to withdraw money
  withdraw(amount) {
    if (amount <= this.#balance) {
      this.#balance -= amount;
    } else {
      console.log('Insufficient funds');
    }
  }

  // Public method to check balance
  checkBalance() {
    return `Your account balance is $${this.#balance}`;
  }
}

// Create an instance of BankAccount
const account1 = new BankAccount('123456', 1000);

// Access public methods
account1.deposit(500);
console.log(account1.checkBalance()); // Output: Your account balance is $1500
account1.withdraw(2000); // Output: Insufficient funds

Explanation

  • Private Property: The #balance property is private and cannot be accessed directly from outside the class.
  • Public Methods: Methods like deposit(), withdraw(), and checkBalance() are public and can be accessed to interact with the private property.
  • Encapsulation: By encapsulating the balance, we ensure that it can only be modified through the defined methods, which adds a layer of security and control.

Static Methods and Properties

Static methods and properties are those that belong to the class itself rather than the instances of the class. They can be accessed directly using the class name without creating an instance.

Syntax of Static Methods and Properties

// Define a class with static methods and properties
class MyClass {
  // Static property
  static myStaticProperty = 'Static Property';

  // Static method
  static myStaticMethod() {
    return 'This is a static method';
  }
}

Example: Static Methods and Properties in JavaScript

// Define a MathUtils class with static methods
class MathUtils {
  // Static method to add two numbers
  static add(a, b) {
    return a + b;
  }

  // Static method to multiply two numbers
  static multiply(a, b) {
    return a * b;
  }
}

// Access static methods directly using the class name
console.log(MathUtils.add(5, 3)); // Output: 8
console.log(MathUtils.multiply(4, 6)); // Output: 24

Explanation

  • Static Property: Defined using the static keyword. It belongs to the class and can be accessed directly.
  • Static Method: Also defined using the static keyword. It can be called directly on the class without needing an instance.
  • Use Case: Static methods are often used for utility functions that don’t require any instance-specific data.

Abstract Classes (ES2022+ Feature)

An abstract class is a class that cannot be instantiated on its own and is meant to be extended by other classes. It can contain abstract methods, which must be implemented by the subclass.

Syntax of Abstract Classes

// Define an abstract class
abstract class Animal {
  // Abstract method
  abstract speak(): string;

  // Regular method
  move() {
    return 'Moving...';
  }
}

// Subclass extending the abstract class
class Dog extends Animal {
  // Implement the abstract method
  speak() {
    return 'Woof!';
  }
}

Example: Using Abstract Classes

// Define an abstract class Shape
abstract class Shape {
  // Abstract method
  abstract calculateArea(): number;

  // Regular method
  getType() {
    return 'This is a shape';
  }
}

// Subclass Circle extending Shape
class Circle extends Shape {
  constructor(private radius: number) {
    super();
  }

  // Implement the abstract method
  calculateArea() {
    return Math.PI * this.radius * this.radius;
  }
}

// Create an instance of Circle
const circle = new Circle(5);
console.log(circle.calculateArea()); // Output: 78.53981633974483
console.log(circle.getType()); // Output: This is a shape

Explanation

  • Abstract Class: Defined using the abstract keyword. It cannot be instantiated directly.
  • Abstract Method: Declared using the abstract keyword and must be implemented by the subclass.
  • Regular Method: Methods that are not abstract and can be inherited by subclasses.
  • Use Case: Abstract classes are useful when you want to define a common interface for different implementations.

Frequently Asked Questions (FAQs)

1. What is the difference between a class and an object?

A class is a blueprint or template for creating objects, while an object is an instance of a class. The class defines the properties and methods that the object will have, whereas the object is the actual entity created from the class.

2. Why should I use classes in JavaScript?

Classes in JavaScript provide a clear and organized way to create objects and promote code reuse through inheritance and encapsulation. They make the code more readable, maintainable, and scalable.

3. Can I create a class without a constructor?

Yes, if you don’t define a constructor, JavaScript will automatically provide a default constructor that doesn’t initialize any properties. However, it’s a good practice to define a constructor if you need to initialize properties.

4. How do I create a single instance of a class in JavaScript?

You can create a singleton class by controlling the instantiation process, often by using a private constructor and a static method that returns the single instance. However, this is more of a design pattern and not directly related to the class syntax itself.

5. What is the purpose of the super() keyword in a subclass constructor?

The super() keyword is used to call the constructor of the superclass (parent class) when creating a subclass. It initializes the properties defined in the superclass and is essential for proper inheritance.

Conclusion

Classes in JavaScript provide a robust framework for building object-oriented applications. By understanding the concepts of classes, inheritance, encapsulation, and static methods, you can create organized, reusable, and maintainable code. Start by defining your own classes, experimenting with inheritance, and exploring the various features JavaScript has to offer.

Index
Scroll to Top