With the help of Encapsulation, you can easily bind the data or a single unit to the methods that are performing some operations on it. It also permits you to validate and control the data flow in a JavaScript application.
This write-up will explain Encapsulation in JavaScript with the help of suitable examples. So, let’s start!
Encapsulation in JavaScript
Encapsulation in JavaScript is a methodology used for hiding information. It is based on the concept that object properties should not be exposed publicly to the outside world. Implementing Encapsulation in JavaScript prevents access to the variables by adding public entities inside an object, which the callers can use to achieve specific results.
Example: Implementing Encapsulation in JavaScript
First of all, we will create a JavaScript object named “student” having a “name” property:
name : "Alexander",
};
In the next step, we will print out the initial value of the “name” property:
Then, we will modify the “student.name” property value and again utilize the “console.log()” method to display it in the console:
console.log("student name is : "+ student.name);
student.name = "Paul";
console.log("student name is : "+ student.name);
Output
As you can see, everything is working perfectly according to the added logic. However, a problem will arise when a user inputs an integer value for the “student.name” property.
Example: Validating data with Encapsulation methods in JavaScript
A JavaScript variable can hold a value of any data type, so to resolve the mentioned issue, we have to limit the range of legal characters for the “name” property value. For this purpose, we will utilize a Regex Expression “/\d+/” that will keep a check on “one or more occurrences of the digit characters (0-9)“. This Regex Expression will be added in a new setter method, “setName” which performs further testing:
name: "Alexander",
setName: function (value) {
var expression = new RegExp(/\d+/);
if (expression.test(value)) {
console.log("Invalid Name is entered");
}
else {
this.name = value;
}
}
Next, we will add a getter method “getName” to retrieve the “student.name” property value:
return this.name;
}
};
console.log(student.getName());
student.setName("Max");
console.log(student.getName());
student.setName(34);
console.log(student.getName());
Now, If the statement “expression.test(value)” evaluates to be “true,” then a message will be displayed on the console window stating that “Invalid Name is entered”, otherwise the “value” passed as an argument will be assigned to the “name” property:
We have successfully performed the validation using a Regex Expression in the setter method, but our program is not fully encapsulated. That’s because the “name” property is declared globally, which permits the caller to access and modify its value:
console.log(student.getName());
The above-given output shows that when we have directly accessed the “name” property of the “student” object, validation does not happen, and “34” is set as the property value. This action proves that if an object’s property is available globally, it can be easily accessed, which risks the security of the data.
Encapsulation in JavaScript using Function Scope
Rather than exposing the object’s properties; we need to hide it from the outside. To do so, you can use the “var” keyword to define a private property and enclose it in the scope of a function.
Example: Encapsulation in JavaScript using Function Scope
In the following “newFunc()” definition, “x” is a private variable which can be accessed within the function’s body:
{
var x = "linuxhint.com";
console.log(x);
}
console.log(x);
Execution of the provided code shows an error because “x” is defined in the “newFunc()” and we are accessing it in terms of Global scope:
Similarly, adding “name” as a private variable within the “setter” method will restrict its direct access. In this scenario, the “name” variable can not be utilized outside of the “setter” method scope, which means that the “getter” method can not access it too.
Using “Closures” is the simplest and most elegant way to implement Encapsulation in JavaScript.
Encapsulation in JavaScript using Closures
Inside a parent function, “Closures” allow a function to utilize another function’s local variable.
For instance, we have a private variable “name“, which can be accessed by both methods “getName” and “setName” within the function scope. As a result, anytime the anonymous function is invoked, it must return the inner object and assign it to an outside variable.
Example: Encapsulation in JavaScript using Closures
In this example, when we invoke the “setName()” and “getName()” functions, this action generates a new invocation closure scope. The scope is then preserved by returning a pointer to the “student” object:
var name = "Alexander";
var expression = new RegExp(/\d+/);
return {
setName: function (value) {
if (expression.test(value)) {
console.log("Invalid Name is entered");
}
else {
name = value;
}
},
getName: function () {
return name;
}
};
}();
The given function ending with “()” indicates that we are invoking the function and assigning the returned value to the “student” variable:
student.setName("Max");
console.log(student.getName());
student.setName(76);
student.name = 76;
console.log(student.getName());
In this case, Encapsulation is fully implemented using Closures, and the callers can not access the private variable directly:
That was all about the basic information related to Encapsulation in JavaScript; you can further explore it according to our requirements.
Conclusion
Using Function scopes and Closures, Encapsulation in JavaScript can be implemented easily. With the help of Encapsulation, you can bind the data or a single unit to the methods that are performing some operations on it. It also permits you to validate and control the data flow in a JavaScript application. This write-up explained Encapsulation in JavaScript along with suitable examples.