Oops
Encapsulation in JavaScript
In this tutorial, we will learn about encapsulation in JavaScript.
Encapsulation is one of the four fundamental OOP concepts. It is the bundling of data and the methods that operate on that data into a single unit, i.e., class. It is used
- to hide the internal state of an object from the outside world and to only expose the necessary functionality.
- to prevent the accidental modification of data.
- to provide a way to access the data in a controlled manner.
JavaScript uses closures to implement encapsulation, which allows developers to create private variables and methods that cannot be accessed from outside the object.
Example
function Person(name, age) {
let privateName = name;
this.age = age;
this.getName = function () {
return privateName;
};
}
let person = new Person("John", 25);
console.log(person.name); // undefined
console.log(person.age); // 25
console.log(person.getName()); // JohnIn the above example, the privateName variable is a private variable that cannot be accessed from outside the object. The getName method is a public method that can be accessed from outside the object.
Conclusion
- Encapsulation is the bundling of data and methods that operate on that data into a single unit.
- JavaScript uses closures to implement encapsulation.
- Encapsulation is used to hide the internal state of an object from the outside world and to only expose the necessary functionality.
- Encapsulation is used to prevent the accidental modification of data.
- Encapsulation is used to provide a way to access the data in a controlled manner.
How is this guide?
Sign in to share your feedback
Help us improve by sharing your thoughts on this guide.
Last updated on