In JavaScript, Encapsulation is a fundamental concept in object-oriented programming that involves bundling the data (properties) and the methods (functions) that operate on the data into a single unit, known as a class or object.
Encapsulation helps in organizing and protecting the internal implementation details of an object, providing a clear separation between the internal structure and the external interface.
Here are some key aspects of encapsulation in JavaScript:
JavaScript does not have built-in support for private members (properties and methods) within a class. However, developers often use conventions and patterns to achieve a form of encapsulation.
One common convention is to prefix private properties and methods with an underscore "_".
"_" indicates that these members are intended for internal use and should not be accessed directly from outside the class.
class Car { constructor(make, model) { this._make = make; // Private property this._model = model; // Private property } _startEngine() { // Private method console.log("Engine started"); } drive() { // Public method this._startEngine(); console.log("Car is moving"); } } const myCar = new Car("Toyota", "Camry"); myCar.drive(); // Outputs: Engine started, Car is moving
class Person { constructor(name, age) { this._name = name; this._age = age; } get name() { return this._name; } set age(newAge) { if (newAge >= 0) { this._age = newAge; } else { console.error("Age cannot be negative"); } } } const john = new Person("Alice", 23); console.log(john.name); // Accessing the getter john.age = 24; // Calling the setter
JavaScript supports getters and setters, which allow controlled access to the private properties of an object.
Getters allow reading the value of a private property, and setters allow modifying the value, typically with some validation.