Closures – How To Create Reusable Functions
Bind And Apply
Bind and apply are functions that allow you to create a new function with explicitly defined arguments, or you could wrap the call in another function to create one that takes varying arguments. Here’s an example of a bound function:
As you can see in the screenshot, sayTim is now bounded up and uses sayMyName to create a new version for Tim. Now, we could do this anytime we want to create a new function based on an old function. But the problem is bind and apply are not well suited for partial application. What is partial application you might ask?
Partial application is the process giving a function only part of its arguments. This allows us to create functions that can be passed arguments for later, and this also means we can’t create complex functions using bind and apply. Now, if we want to create complex functions, we need to use closures!
As you can see we simply returned a function from a function. When we do this, we can close a scope around variable we pass in allowing us to save those variables for the inner function. This allows us to create new functions often in a single line.
Now this example might seem weird to you. Why would I ever want to use this you say? Normally, you wouldn’t need to bind up a name to a single variable like that. This code isn’t doing anything I couldn’t do manually! In fact, I can’t think of any reason why you wouldn’t just pass ‘Tim’ as the argument. But, let’s look at a less trivial example: creating different kinds of people.
The problem in this program is that we need to create programmers and consultants all with different names for our company. Our company wants a list of these people sorted by job type. Here’s the class for creating people that you must use creating by another programmer:
The people also may have extra parameters defined in their options other than their job. I will show you how to do this in the normal way, and the closure way.
In this example, we create two new functions for creating programmers and consultants. They both do exactly the same thing, with one difference of changing the job property (We could have optimized this with a for loop or using two lists). After that, we declare a list of workers and push our programmers and consultants into them. Now, this is alright, but it sucks because we basically had to write the same thing twice. Here’s one that makes it a single function, but adds more clutter:
Now, Let’s optimize this with closures and a little functional magic.
Console Output Of Every Way
As you can see each way does the exact same thing, but the closure and optimized normal way allow us to create people of multiple different jobs. However, the closure way wins out in one way: We can create functions that look more readable in a single line.
Anyway, I hope this tutorial was helpful and added a new skill to your toolbelt.