Lets talk about some Closure
First, lets start with a definition.
This definition comes from the Mozilla Developer Network
“Closures are functions that refer to independent (free) variables (variables that are used locally, but defined in an enclosing scope). In other words, these functions ‘remember’ the environment in which they were created.”
Lets focus on that last sentence and apply it to some examples.
First we have a function helloWorld(), inside this function there is a variable hello and another function declaration say(). Say() is being returned from the outer function.
HelloWorld is invoked and the return value, function say(), is assigned to sayHelloWorld. SayHelloWorld is then invoked. SayHelloWorld() or Say() has a closure over the inner scope of helloWorld. No matter where in our program say() is invoked, it will remember its original scope and have access to the variable hello.
This next example is of a function counter() that returns an object . Each of the methods on the returned object reference the total variable defined in the counter() function. Once we invoke the counter() function we have created the closure.
The total variable is now private and can only be accessed by the 3 methods that were returned by counter(). Each time we invoke counter we are creating a new instance. You can create as many counters as you wish, each with its own private total. Closure is being used here to essentially hide the total variable from the surrounding environment.
This last example is similar to the first. The setup is the same, an outer function secretIdentity and the inner function getIdentity() is logging the variable name. But this time, rather than returning the inner function, we are passing it as a value to the helper function whoAreYou(), where it is invoked. Because getIdentity() remembers the enviroment in which it was created, we can call it elsewhere and it will still work as expected! Closure is allowing you to pass functions as values.
I hope these few examples have helped shed some light on what closure looks like and how it is used. If things are still a little foggy I encourage you to check out the link to the Modzilla Developer Network at the top of this article. It’s a great resource for everything web related.
Thanks for reading!