As the definition goes, closures are the inner functions in JavaScript, that has the access to the private variables. If that is not enough, consider the following example for instance.
As shown in the above code, name is the property of the function Person, and is accessible from the objects of that function. The output of the above method would be, yes you guessed it, Neelesh.
Now let’s modify the code a bit and see what happens. Consider the following code.
The output of the above code will be like:
Let’s stop here for a moment and analyze what actually happened. Before hand, the property name was the property of the function Person and therefore was accessible to every object of Person. Lately the property was changed to just be a private variable. On doing so, it looses its scope and became inaccessible. The objects of Person would now have no idea to whether or not the property name even exists and hence it has thrown ‘undefined’. Now, let us bring closures into the picture.
So, as you can see from the above figure, the function getName or our closure function as being the inner function of Person, can access its private variable. And this getName function, on being the property of the function Person, can be access by the objects of Person. The output if the above code would be:
Cool! Now if you see it closely, there is a subtle difference between our first approach and this one however. In the former case, we can at any point, can modify the value of the variable name of function Person which could lead to adverse effect on our code at the latter stage. Like:
1: person.name = "This is the fake test name";
But with the latter approach, (the closure one, of course), we don’t have access to the property name at the first place, and hence, we cannot modify it.
I hope this post would have lead the basic understanding of closures.
Happy Reading!!!
0 comments