JavaScript is the most popular client-side language for the last decade and now many users feeling bored with page reload system in any web apps or site. They want the access without page reload and that’s why JavaScript is heavily used in any site. Now in this article, I will discuss a JavaScript module pattern features that is closures. Those who have knowledge in Java, they also know that Java provides the ability to declare a function private means, the function only can access from any other function inside the same class. JavaScript does not provide a native way of doing this, but it is possible to emulate private methods using closures.
Closure:
A closure is an inner function that has access to the outer function’s and their variables. The closure has three scope chains: it has access to its own scope, it has access to the outer function’s variables, and it has access to the global variables.
I have given an example in the below. If you follow this you will get the clear knowledge of closures, so follow the code.
Script Code:
var myFunction = (function(){ var privateVar = 0; function changePrivateVar(val){ privateVar = privateVar + val; } return { increseVar : function(){ changePrivateVar(1); }, decreseVar : function(b){ changePrivateVar(b); }, getVar : function(){ return privateVar; } } }); var myObject = myFunction();
Now, we test the code by using the console. So, here I have declared a function named changePrivateVar and I kept it as a private function. So if we try to access this function outside the myFunction it will definitely give an error, because it’s private.
myObject.changePrivateVar(-5);
Output:
Uncaught TypeError: myObject.changePrivateVar is not a function
Now if we access this function throw the other function means, increseVar or decreseVar then there is no problem. So let’s check.
myObject.increseVar(2); console.log(myObject.getVar());
Output:
2
That’s all, and you have understood the difference between these two examples. And try to use this in your script for making it more secure.