Javascript OOPs: JavaScript Encapsulation

Javascript Encapsulation

JavaScript Encapsulation is part of the object-oriented programming patterns used to build effectively build complex programs on both the server and the client. However, the more sophisticated the implementation, the more maintainable and adaptable the code required to deal with the problem. Encapsulation, one of the Object-Oriented Programming concepts, is the key to achieving such aims.

Encapsulation is simply the bundling of data and the techniques that operate on that data so that access to such data from outside the bundle is restricted. You do not reach out and directly manipulate some object's props to change its contained state. Instead, you invoke a method on the object, and it may respond by altering its state.

To have in-depth knowledge of Encapsulation, you need to understand properly understand Javascript classes. Creating classes and controlling how it is accessed from outside should be the basic knowledge of Encapsulation.

Advantages of Javascript Encapsulation

The key benefit of employing encapsulation in JavaScript is that it secures the data. Encapsulation also has the following advantages:

  • Encapsulation protects a thing against unauthorized access.
  • Encapsulation aids in attaining a level without disclosing its intricate features.
  • This will help to decrease human mistakes.
  • Make the app more adaptable and controllable.
  • The application is made simpler.

How JavaScript Encapsulation Works

Consider a basic scenario in which an "employee" object has two attributes: the "name" attribute.

var employee = {
name : "Carol Danvers",
};
alert(employee.name); // Carol Danvers
employee.name = "Diana Mitchell";
alert(employee.name); // Diana Mitchell

In the above scenario, everything appears to be in order. We made the object, printed its attribute value, and then changed it. However, the issue appears to develop when a user attempts to set an integer value to the name property.

Now that you understand the advantages of Javascript Encapsulation and how to improve your code. Getting the full grasp of Javascript OBJECT ORIENTED PROGRAMMING should be the priority. Our OOP Pages are aggregated here

employee.name = "Jack Sparrow";
alert(employee.name); // Jack Sparrow

This is perfectly allowed in JavaScript since a variable can take any type that is passed to it. To correct this, we must define the range of permissible characters that may be assigned to the object's attribute name. These Validations will fail if the caller has access to and can change the value of these javascript variables. The simplest solution would be

var employee = {
name : "Carol Danvers",
setName : function (value) {
var exp = new RegExp(/\d+/);
if( exp.test(value) ) {
alert("Invalid Name");
}
else {
this.name = value;
}
},
"getName" : function() {
return this.name;
}
};
alert( employee.getName() );   // Carol Danvers
employee.setName( "Diana Mitchell" );
alert( employee.getName() );   // Diana Mitchell
employee.setName( 42 );        // Invalid Name
alert( employee.getName() );   // Diana Mitchell

The example above uses validation in javascript encapsulation. However, it still has some flaws because the caller can modify the name if he accesses it directly.

employee.setName( 42 ); // Invalid Name; Here name will not be changed.
employee.name = 42;     // No validation will happen and the name is changed
alert( employee.getName() );   // 42 will be printed.

The final objective here is to prevent the variable name from being exposed globally with the object "employee." It is aided by javascript encapsulation. The notions - Closures and Function Scope can help with this.

1. Function Scope

Any variable written within the code block of the functions is concealed from the outside. Understand how to create simple readable Javascript function here

function javascriptencapsulation()
{
var fnVar = "Hello!";
alert( fnVar ) // "Hello!";
}
alert( fnVar ) // error; fnVar cannot be accessed outside the function.

As a result, if we relocate the variable "name" within the function "setName," the callers will no longer be able to get direct access. However, it is difficult to place the variable "name" immediately within the function "setName" since variables inside a function block cannot be used outside of its scope. Therefore, name would not be available for the "getName" method. Closure will be beneficial in this regard.

2. Closures

Closure occurs when two functions are wrapped together with references to their lexical context or to their surrounding state. In layman's terms, closure provides access to a function's local variable for usage by another function within a parent function. We have a variable name hidden from the outside within the function setName. However, the inner object (myObj) has access to it:

var employee = function () {
var name = "Carol Danvers";
var exp = new RegExp(/\d+/);
var myObj = {
setName : function (value) {
if( exp.test(value) ) {
alert("invalid name");
}
else {
name = value; // The object will have access to "name"
}
},
getName : function () {
return name; // The object will have access to "name"
}
}; // End of the Object
};
employee.getName(); // does not work!

Now that we've exploited the idea of closure, both methods may access the inner object myObj. However, there is a flaw in accessing the inner object. Employee was seen above. Neither getName nor employee may be used. myObj. getName may be used because myObj is also private to the function, and we know that private variables cannot be accessed outside of the function in this manner. As a result, anytime the anonymous function is invoked, we must return the inner object and then assign it to an outer variable. Experienced programmers must understand javascript encapsulation in other to write better, safe, and reusable code.

var employee = function () {
var name = "Carol Danvers";
var exp = new RegExp(/\d+/);
return {
setName : function (value) {
if( exp.test(value) ) {
alert("Invalid Name");
}
else {
name = value;
}
},
getName : function () {
return name;
}
}; // end of the return
}(); // Note this '()' means we are calling the function
// after which the returned result is assigned to the variable employee
alert(employee.getName());   // Carol Danvers
employee.setName( "Rahul Khanna" );
alert(employee.getName());  // Diana Mitchell
employee.setName( 42 ); // Invalid Name; the name does not change.
employee.name = 42;     // Does not have any effect on the private fullName variable.
alert(employee.getName());  // Diana Mitchell is printed again.