Encapsulation in JavaScript
In this module, we'll be reading about encapsulation in JavaScript which is a very important OOPs concept which means the packing of data and functions into one component and then controlling access to that component.
Encapsulation
Encapsulation in JavaScript is a very important concept of Object Oriented Programming, along with inheritance, abstraction, polymorphism. It is a fundamental concept in object-oriented programming that helps in organizing and controlling access to the properties and methods of an object. It enables data hiding and ensures that the internal implementation details of an object are not directly exposed to the outside world.
In JavaScript, encapsulation can be achieved through the use of closures and constructor functions or ES6 classes. Here's an example that demonstrates encapsulation using constructor functions:
For example:
function Person(name, age)
{
var privateName = name; // private variable
this.getAge = function()
{
return age; //public method accessing private variable
};
this.setAge = function(newAge)
{
age = newAge; // public method modifying private variable
};
this.getName = function()
{
return privateName; // public method accessing private variable
};
}
// Creating an instance of Person
var person = new Person("John", 25);
console.log(person.getName()); // Output: John
console.log(person.getAge()); // Output: 25
person.setAge(30);
console.log(person.getAge()); // Output: 30
In the example above, the Person constructor function creates objects with private and public members. The privateName variable is encapsulated within the constructor function and is not directly accessible from outside. The getAge and setAge methods provide controlled access to the age property, allowing read and write operations. Similarly, the getName method provides read-only access to the privateName variable.
Note that the example uses the concept of closures to create private variables (privateName) and functions (getAge, setAge, getName). The private variables are accessible within the scope of the constructor function, but not directly accessible outside of it. The public methods, on the other hand, have access to the private variables due to the concept of closures.
Conclusion
By encapsulating the data and providing controlled access through methods, encapsulation helps in maintaining data integrity, hiding implementation details, and allowing the object to enforce its own rules and constraints.