Please read my previous post “Let’s Talk About Scopes Baby…” before you continue on as a proper understanding of Scopes is necessary to grasp the beauty of the closure.
Closures are functions that consist of a function within a function, so an outer function and an inner function. Below is a basic example of a closure function:
Below is what is printed to the console:
to the console. If I call the .toString() method on innerCall this is what is logged :
Essentially the variable innerCall now contains the function that was returned from the outerFunc function, making it invocable. The cool thing is that the variables from outeFunc are still available to innerCall so when it is invoked it has access to it’s own variable and can access the outer functions variables by reference. Below is an example of how this could come in handy :
Pretty straight forward right? I hope this has shed some light on closures and their uses, if you have any questions feel free to comment.
So what is a Scope?
The Global scope is the main window or window object, any variable or function that is declared within the global scope is accessible anyplace in your code. For example, think of the global scope as a fish tank, within the fish tank there is a castle (function) and two fish (variables). You as a human can access anything within the fish tank and manipulate it however you please.
Below is code snippet that ties my fish tank example and code together.
Keep in mind you cannot see the window object (fish tank) but it’s there.
Now there is one more Scope that is a little more involved when it comes to it’s understanding and that is the infamous Closure Scope. I will be covering this concept more in depth in another post, just to make sure I get to all the ins and outs of the subject.
If you have any questions about this specific example please feel free to contact me or leave a comment.