Pooja Singhal

Digital Marketing & Javascript Tips & Updates

Object-Oriented Programming in JavaScript

Object-Oriented Programming (OOP) is a programming paradigm that focuses on creating reusable and modular code by using objects, classes, and inheritance. JavaScript supports OOP concepts, and here are some key concepts of OOP in JavaScript:

  • Objects: JavaScript is an object-based language, meaning everything in JavaScript is an object. An object is a collection of related data and functions that represent a real-world entity. Objects in JavaScript can be created using object literals, constructor functions, and ES6 classes.
  • Classes: A class is a blueprint for creating objects that encapsulate data and behavior. JavaScript introduced classes in ES6, and they allow you to define the structure and behavior of an object. You can create an instance of a class using the new keyword.
  • Inheritance: Inheritance allows you to create a new class that is a modified version of an existing class. JavaScript supports inheritance through prototypal inheritance, where objects inherit properties and methods from their prototype object.
  • Encapsulation: Encapsulation refers to the practice of hiding the implementation details of an object from outside access, allowing the object to be more modular and easier to use. Encapsulation can be achieved in JavaScript using closures or by using private class members with the # symbol.
  • Polymorphism: Polymorphism is the ability of an object to take on multiple forms. In JavaScript, polymorphism can be achieved through function overloading and method overriding.

Here’s an example of how to use Object-Oriented Programming concepts in JavaScript:

// Define a class
class Animal {
  constructor(name, sound) {
    this.name = name;
    this.sound = sound;
  }

  makeSound() {
    console.log(`${this.name} says ${this.sound}`);
  }
}

// Define a subclass that extends Animal
class Dog extends Animal {
  constructor(name) {
    super(name, 'woof');
  }

  wagTail() {
    console.log(`${this.name} wags its tail`);
  }
}

// Create an instance of the Dog class
const myDog = new Dog('Rex');

// Call the methods of the Dog class
myDog.makeSound(); // Output: Rex says woof
myDog.wagTail(); // Output: Rex wags its tail

In this example, we define an Animal class with a constructor that takes a name and sound parameter, and a makeSound method that logs the animal’s name and sound to the console.

We then define a Dog subclass that extends Animal and has its own constructor that takes a name parameter. The Dog subclass also has a wagTail method that logs a message to the console.

Finally, we create an instance of the Dog class called myDog and call its makeSound and wagTail methods.

Vikas Saini

Back to top