JavaScript Encapsulation
Encapsulation is a fundamental principle of Object-Oriented Programming (OOP) that restricts direct access to some of an object's components, which helps to prevent accidental interference and misuse of data. In JavaScript, encapsulation is often achieved using classes, private fields, and methods.
Encapsulation Syntax
class ClassName {
// Private field (requires # before the field name)
#privateField;
constructor(value) {
this.#privateField = value; // Accessing private field
}
// Getter method to access the private field
getPrivateField() {
return this.#privateField;
}
// Setter method to modify the private field
setPrivateField(value) {
this.#privateField = value;
}
}
Key Features of Encapsulation:
- Encapsulation helps in protecting data from unauthorized access and modification.
- Private fields and methods (prefixed with `#`) restrict access from outside the class.
- Getters and setters allow controlled access to private fields.
Example: Implementing Encapsulation
Example
class User {
#username; // Private field
constructor(username) {
this.#username = username; // Initializing private field
}
// Getter method
getUsername() {
return this.#username;
}
// Setter method
setUsername(newUsername) {
this.#username = newUsername;
}
}
// Using the class
const user = new User("JohnDoe");
console.log(user.getUsername()); // Output: JohnDoe
user.setUsername("JaneDoe");
console.log(user.getUsername()); // Output: JaneDoe
Output
JohnDoe
JaneDoe
JaneDoe
Explanation of Code:
- The #username field is private and cannot be accessed directly outside the class.
- The getUsername() method provides controlled access to the private field.
- The setUsername() method allows controlled modification of the private field.
Advantages of Encapsulation:
- Protects the integrity of data by controlling how it is accessed and modified.
- Makes code more modular and easier to maintain.
- Hides implementation details and exposes only necessary functionality.