DEV Community

Abhay Yt
Abhay Yt

Posted on

Mastering JavaScript Classes: A Complete Guide to Modern OOP

Understanding JavaScript Classes

JavaScript classes are a syntactical sugar over its prototypal inheritance system. Introduced in ES6, classes provide a clear and structured way to define objects and work with inheritance in JavaScript, making the code more readable and organized.


Defining a Class

You can define a class using the class keyword.

Example:

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

  greet() {
    console.log(`Hello, my name is ${this.name} and I am ${this.age} years old.`);
  }
}

const person1 = new Person("Alice", 25);
person1.greet(); // Hello, my name is Alice and I am 25 years old.
Enter fullscreen mode Exit fullscreen mode

Key Features of Classes

  1. Constructor Method: The constructor is a special method for initializing new objects. It is called automatically when a new instance of the class is created.

Example:

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

   const myCar = new Car("Toyota");
   console.log(myCar.brand); // Toyota
Enter fullscreen mode Exit fullscreen mode
  1. Methods: Functions defined inside a class are called methods.

Example:

   class Animal {
     sound() {
       console.log("Animal makes a sound");
     }
   }

   const dog = new Animal();
   dog.sound(); // Animal makes a sound
Enter fullscreen mode Exit fullscreen mode
  1. Static Methods: Methods defined with the static keyword belong to the class itself, not instances of the class.

Example:

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

   console.log(MathUtils.add(3, 5)); // 8
Enter fullscreen mode Exit fullscreen mode
  1. Getters and Setters: Special methods to access and modify properties.

Example:

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

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

   const rect = new Rectangle(10, 5);
   console.log(rect.area); // 50
Enter fullscreen mode Exit fullscreen mode

Inheritance in Classes

Inheritance allows a class to acquire properties and methods from another class using the extends keyword.

Example:

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

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

class Dog extends Animal {
  speak() {
    console.log(`${this.name} barks.`);
  }
}

const dog = new Dog("Rex");
dog.speak(); // Rex barks.
Enter fullscreen mode Exit fullscreen mode

Private Fields and Methods

Private fields and methods, introduced in ES2022, start with a # and cannot be accessed outside the class.

Example:

class BankAccount {
  #balance;

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

  deposit(amount) {
    this.#balance += amount;
    console.log(`Deposited: ${amount}`);
  }

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

const account = new BankAccount(100);
account.deposit(50); // Deposited: 50
console.log(account.getBalance()); // 150
// console.log(account.#balance); // Error: Private field '#balance' must be declared in an enclosing class
Enter fullscreen mode Exit fullscreen mode

Class Expressions

Classes can also be defined as expressions and assigned to variables.

Example:

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

  getArea() {
    return this.width * this.height;
  }
};

const rect = new Rectangle(10, 5);
console.log(rect.getArea()); // 50
Enter fullscreen mode Exit fullscreen mode

Mixing with Prototypes

While classes are syntactic sugar, you can still combine them with JavaScript’s prototype-based inheritance.

Example:

class Person {}
Person.prototype.sayHello = function () {
  console.log("Hello!");
};

const person = new Person();
person.sayHello(); // Hello!
Enter fullscreen mode Exit fullscreen mode

Best Practices with Classes

  1. Encapsulation:

    Use private fields to protect sensitive data.

  2. Reusability:

    Leverage inheritance to reuse code across multiple classes.

  3. Avoid Overcomplication:

    Use classes only when necessary. Simple objects or functions might suffice for small tasks.

  4. Consistency:

    Follow naming conventions for methods and properties for readability.


Conclusion

JavaScript classes provide a clean and efficient way to manage object-oriented programming in JavaScript. With features like inheritance, static methods, private fields, and encapsulation, they offer powerful tools to structure and manage code, making it easier to build scalable and maintainable applications.

Hi, I'm Abhay Singh Kathayat!
I am a full-stack developer with expertise in both front-end and back-end technologies. I work with a variety of programming languages and frameworks to build efficient, scalable, and user-friendly applications.
Feel free to reach out to me at my business email: kaashshorts28@gmail.com.

Top comments (0)