DEV Community

Abhay Singh Kathayat
Abhay Singh Kathayat

Posted on

Object-Oriented Programming (OOP) in JavaScript: A Comprehensive Guide

Object-Oriented Programming (OOP) in JavaScript


1. Objects and Classes

In JavaScript, objects are collections of key-value pairs (properties and methods). Classes serve as blueprints to create objects.

Example:

// Define a class
class Person {
  constructor(name, age) {
    this.name = name; // Property
    this.age = age;
  }

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

// Create an object
const person1 = new Person('Alice', 25);
person1.greet(); // Output: Hello, my name is Alice and I am 25 years old.
Enter fullscreen mode Exit fullscreen mode

2. Encapsulation

Encapsulation means bundling data (properties) and methods that manipulate the data inside a single unit (object). It restricts direct access to certain parts of an object.

Example:

class BankAccount {
  #balance; // Private field

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

  deposit(amount) {
    this.#balance += amount;
  }

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

const account = new BankAccount(1000);
account.deposit(500);
console.log(account.getBalance()); // 1500
// console.log(account.#balance); // Error: Private field '#balance' not accessible
Enter fullscreen mode Exit fullscreen mode

3. Inheritance

Inheritance allows a class to inherit properties and methods from another class. It helps reuse existing code.

Example:

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

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

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

const dog = new Dog('Buddy');
dog.speak(); // Output: Buddy barks.
Enter fullscreen mode Exit fullscreen mode

4. Polymorphism

Polymorphism means having multiple forms. In OOP, it allows methods in child classes to have the same name as methods in the parent class but behave differently.

Example:

class Shape {
  area() {
    return 0;
  }
}

class Rectangle extends Shape {
  constructor(width, height) {
    super();
    this.width = width;
    this.height = height;
  }
  area() {
    return this.width * this.height;
  }
}

const shape = new Shape();
const rectangle = new Rectangle(10, 5);

console.log(shape.area());       // 0
console.log(rectangle.area());   // 50
Enter fullscreen mode Exit fullscreen mode

5. Abstraction

Abstraction hides the complexity of the code and only shows the essential parts to the user.

Example:

class Vehicle {
  startEngine() {
    console.log('Engine started');
  }
}

class Car extends Vehicle {
  drive() {
    console.log('Driving the car...');
  }
}

const car = new Car();
car.startEngine(); // Engine started
car.drive();       // Driving the car...
Enter fullscreen mode Exit fullscreen mode

6. Static Methods and Properties

Static methods and properties belong to the class itself, not to the instances.

Example:

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

console.log(MathUtils.add(5, 3)); // 8
Enter fullscreen mode Exit fullscreen mode

7. Prototypes

JavaScript uses a prototype-based inheritance model, where objects can inherit properties and methods from other objects.

Example:

function Person(name) {
  this.name = name;
}

Person.prototype.greet = function() {
  console.log(`Hello, my name is ${this.name}`);
};

const person = new Person('Alice');
person.greet(); // Hello, my name is Alice
Enter fullscreen mode Exit fullscreen mode

Key Takeaways

  1. Use classes to create blueprints for objects.
  2. Encapsulate properties with private fields using #.
  3. Use inheritance (extends) to reuse code.
  4. Override methods for polymorphism.
  5. Simplify interactions with abstraction.
  6. Leverage static methods and prototype inheritance.

JavaScript’s OOP features allow developers to write clean, modular, and reusable code.

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)