Flat Preloader Icon

JS Encapsulation

Encapsulation is a fundamental principle of object-oriented programming (OOP) that refers to the bundling of data and methods that operate on that data into a single unit, called a class. In JavaScript, encapsulation is achieved through the use of classes, objects, and access modifiers.

Key Concepts:

  • Classes:

    • Classes are blueprints for creating objects with specific properties and behaviors. They encapsulate data (properties) and functionality (methods) related to a specific entity.
  • Objects:

    • Objects are instances of classes. They encapsulate their own set of data and methods based on the blueprint provided by their class.
  • Access Modifiers:

    • Access modifiers control the access to the properties and methods of a class. In JavaScript, access modifiers are not explicitly defined, but conventionally, properties and methods prefixed with an underscore (_) are considered private and not intended for direct external access.
				
					class Person {
    constructor(name, age) {
        this._name = name; 
        // Encapsulated property
        this._age = age; 
        // Encapsulated property
    }

    // Encapsulated method
    introduce() {
        console.log(`Hello, my name is $
 {this._name} and I am ${this._age} years old.`);
    }
}

// Creating an instance of the Person class
let person1 = new Person("Alice", 30);

// Accessing encapsulated properties 
(not recommended)
console.log(person1._name); 
// Output: Alice

// Calling encapsulated method
person1.introduce();
// Output: Hello, my name is Alice and
I am 30 years old.

				
			

Benefits of Encapsulation:

  • Data Hiding:
      • Encapsulation allows you to hide the internal state of an object and expose only the necessary functionality. This helps prevent direct manipulation of data from outside the class, enhancing data integrity and security.
  • Abstraction:

    • Encapsulation provides a level of abstraction by hiding implementation details and exposing only relevant interfaces. This makes it easier to understand and work with complex systems by focusing on what an object does rather than how it does it.
  • Modularity:

    • Encapsulation promotes modularity by organizing related data and functionality into cohesive units (classes). This improves code organization, readability, and maintainability.

Limitations:

  • JavaScript does not have built-in access modifiers like other OOP languages (e.g., Java, C#). Encapsulation relies on naming conventions and coding conventions to achieve data hiding and encapsulation.