Before we begin, just to recap,
Closure encloses function and the set of variables that were in scope of the function when it was declared. The variables inside the closure kept alive as long as the function alive.
With that in mind, let’s make some closures.
1. Maintain State between function calls
Let’s say you have function
add() and you’d like it to add all the values passed to it in several calls and return the sum. For example,
Of course, you can use a global variable in order to hold the total. But keep in mind that this dude will eat you alive if you (ab)use globals.
For scenarios like this, Closure is the best candidate for maintaining state between function calls without using globals. Let’s see how.
2. Partial application, a.k.a Currying
Suppose you have a function that takes several arguments and you only know values for some of the arguments in the beginning. For this scenario, you can make use of Currying technique to pre-fill the values for known arguments and supply values for the rest of the arguments later.
Here’s an example, illustrating Currying using Closure.
Assume you have a
showMessage() function that shows given message on screen with the given type and position. It takes three arguments. So, every time you want to call this function, you need to supply these three values.
What if you want to make this function call, simpler? What if you create two other methods, namely,
showInfo() that prefill the message type and position and supply the actual message in a later point in time? Let’s Curry them.
As you can see, the
makeCar() function returns an object with two methods:
fillGas. These two methods has access to the private method
burnFuel and private variable
fuel. But the outer world can not directlty access these two.
With that, I am concluding this post of Closure examples. Of course, these are not the only examples of Closures. There are lot many out there. Btw, If you have written closure for an interesting use case, feel free to share it in the comments section.