JS Encapsulation

Encapsulation is a core principle of object-oriented programming that involves bundling the data (attributes) and the methods (functions) that operate on that data into a single unit or class. It also controls access to the data by hiding the internal state and requiring all interaction to be performed through an object's methods.

In JavaScript, encapsulation can be achieved through various techniques, including using closures, private properties, and getter/setter methods.

Key Concepts

1. Private Data Members: Encapsulation involves hiding the internal state of an object from the outside world. In JavaScript, you can use closures or symbols to create private properties that are not accessible directly from outside the object.

2. Public Methods: Access to the private data is controlled through public methods, which act as intermediaries to modify or retrieve the private data. These methods are often called getter and setter methods.

Types of Encapsulation:

Read/Write: Allows both reading and modifying the data. This is achieved using both getter and setter methods.

<script>
class Person {
#name;

constructor(name) {
this.#name = name;
}

get name() {
return this.#name;
}
}
</script>

Write Only: Only allows writing the data. This is less common but can be achieved using only setter methods.

<script> class Person {
#name;
set name(name) {
this.#name = name;
}
}
</script>