Skip to main content

Command Palette

Search for a command to run...

Understanding Object-Oriented Programming in JavaScript

A deep dive into Object-Oriented Programming OOPS

Updated
•6 min read•View as Markdown
Understanding Object-Oriented Programming in JavaScript
S
Software Developer | Full Stack Developer |

What is Object-Oriented Programming (OOPs)?

Object-Oriented Programming (OOP) is a programming paradigm that organizes software design around objects—entities that combine data (attributes) and functions (methods) that operate on that data. Instead of writing procedures that act on data, OOP focuses on creating reusable, self-contained objects that interact by sending messages to each other.

Real-world analogy (blueprint → objects):

Class as a Blueprint: In object-oriented programming, a class is like a blueprint or design document for creating objects. Just as a blueprint defines the structure and specifications for building a house—such as the number of rooms, window placements, and electrical wiring—a class defines the properties (data) and methods (functions) that objects of that class will have.

Object as a Realized Instance: An object is a concrete instance created from a class, much like a real house built from a blueprint. Each house (object) follows the same design but can have unique features—like different paint colors or furniture—just as each object has its own specific values for properties (e.g., a car’s color or speed).

Real-World Example – Car Factory:

  • Blueprint (Class): The design for a "Car" model, specifying features like 4 wheels, an engine, steering wheel, and methods like start(), accelerate(), and brake().

  • Objects (Instances): Individual cars produced from that blueprint—each with its own color, speed, and license plate, but all sharing the same underlying structure and behaviors.

This analogy illustrates instantiation (creating objects from a class), encapsulation (hiding internal mechanics behind simple controls like pedals), and reusability (using the same blueprint to build many different cars).

What is Class in JavaScript?

A class in JavaScript is a blueprint or template for creating objects that encapsulate data (properties) and functions (methods) to manipulate that data. Introduced in ECMAScript 6 (ES6), classes provide a more structured and readable syntax for implementing object-oriented programming (OOP) concepts like encapsulation, inheritance, and polymorphism.

  • Class Declaration: Defined using the class keyword followed by a class name (typically capitalized).

    class Car {
      constructor(brand) {
        this.brand = brand;
      }
      start() {
        console.log(`${this.brand} is starting.`);
      }
    }
    
  • Instance Creation: Use the new keyword to create an object (instance) from a class.

    const myCar = new Car("Toyota");
    myCar.start(); // Output: "Toyota is starting."
    
  • Key Features:

    • Constructor: A special method called automatically when a new instance is created, used to initialize properties.

    • Methods: Functions defined inside the class body, shared among all instances via the prototype.

    • Static Methods/Fields: Belong to the class itself, not instances (e.g., static getClassName()).

    • Inheritance: Use extends and super() to create subclasses that inherit properties and methods.

    • Private Members: Use # prefix for private fields and methods (e.g., #engine).

Creating objects using classes:

Classes in JavaScript provide a structured, modern way to create objects using the class keyword. They act as blueprints for creating instances with shared properties and methods.

Defining a Class

A class is defined using the class keyword followed by a class name (typically capitalized). The constructor method initializes instance properties when a new object is created with the new keyword.

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

  // Instance method
  start() {
    console.log(`\({this.year} \){this.brand} ${this.model} is starting.`);
  }
}

Creating Objects (Instances)

To create an object from a class, use the new keyword followed by the class name and any required arguments.

const myCar = new Car("Toyota", "Corolla", 2021);
myCar.start(); // Output: "2021 Toyota Corolla is starting."

Each new call creates a new, unique instance with its own properties. Instances inherit methods from the class's prototype.

Key Features

  • Constructor: Initializes object properties.

  • Instance Methods: Defined in the class body and shared across all instances.

  • Instance Properties: Set via this inside the constructor.

  • Static Members: Defined with static keyword (e.g., static info()) and belong to the class itself, not instances.

  • Inheritance: Use extends and super() to create subclasses.

Classes are syntactic sugar over JavaScript’s prototype-based inheritance, offering a cleaner, more readable syntax for object-oriented programming.

Constructor Method:

Constructor method in JavaScript is a special method within a class used to create and initialize an object instance of that class. It is automatically called when a new instance is created using the new keyword.

Key Features:

  • Special Syntax: Defined using the constructor keyword inside a class.

  • Initialization: Sets up initial properties and values for the new object using this.

  • Single Definition: A class can have only one constructor method; multiple definitions cause a SyntaxError.

  • Default Constructor: If no constructor is defined, JavaScript provides a default empty constructor.

  • Inheritance: In derived classes, use super() to call the parent class constructor.

Example:

class Car {
  constructor(brand, model) {
    this.brand = brand;
    this.model = model;
  }
  describe() {
    return `This is a \({this.brand} \){this.model}`;
  }
}

const myCar = new Car("Toyota", "Camry");
console.log(myCar.describe()); // "This is a Toyota Camry"

Methods inside a class:

Methods inside a class are functions defined within the class body that define the behavior and actions of objects created from that class. They are essential for encapsulating functionality and promoting code reusability.

  • Instance Methods: These are the most common type of method. They operate on instance variables and require the self parameter (by convention) to access or modify the object's state. They are called on an instance of the class using dot notation (e.g., object.method()).

  • Class Methods: These are defined using the @classmethod decorator and take cls as the first parameter, representing the class itself. They can access and modify class state but not instance state. They are useful for factory methods or when you need to modify class-level data.

  • Static Methods: These are defined using the @staticmethod decorator and do not take self or cls as a parameter. They are utility functions that perform a task in isolation and do not access or modify class or instance state.

What is Encapsulation?

Encapsulation is a fundamental concept in object-oriented programming (OOP) that involves bundling data (variables) and the methods (functions) that operate on that data into a single unit, typically a class. It acts as a protective shield, restricting direct access to the internal state of an object and ensuring that data can only be modified through well-defined public methods, such as getters and setters. This promotes data integrity, security, and maintainability by preventing unauthorized or unintended modifications and allowing controlled access.

  • Core Purpose: To hide internal implementation details and expose only necessary functionality through a public interface.

  • Key Mechanism: Using access modifiers (e.g., private, protected, public) to control visibility of class members.

  • Benefits:

    • Prevents accidental data corruption.

    • Improves code modularity and reusability.

    • Enables changes to internal implementation without affecting external code.

    • Supports other OOP principles like abstraction and polymorphism.