Wednesday, February 19, 2014

Closures in JavaScript

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.

image

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.

image

Now let’s modify the code a bit and see what happens. Consider the following code.

image

The output of the above code will be like:

image

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.

image

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:

image

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!!!

Share this post

0 comments

:) :-) :)) =)) :( :-( :(( :d :-d @-) :p :o :>) (o) [-( :-? (p) :-s (m) 8-) :-t :-b b-( :-# =p~ :-$ (b) (f) x-) (k) (h) (c) cheer

 
© 2013 Neelesh Vishwakarma
Posts RSS Comments RSS
Back to top