Closures

Kino

EIS Game Dev
Veteran
Joined
Nov 27, 2015
Messages
526
Reaction score
743
First Language
English
Primarily Uses
RMMV
The original post can be found here: KinoCreates.io

Closures – How To Create Reusable Functions
Closures are a concept mentioned a lot in JavaScript, and you may not have heard of them. They provide you with a power that’s very similar to bind and apply in Javascript. The advantage is, unlike bind, you can create more robust functions without explicitly defining the parameters. Today, we’re going to show you how they work and how you can make reusable functions in JavaScript with them. But first, let’s talk bind and apply.

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!

Closures
Because JavaScript functions are objects, we can pass them around to other functions and objects like any other variable in our program. Closures, leverage this power to create a similar, but more robust effect of bind and apply. Here’s the above example using a closure and the previous sayMyName function:


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

Normal 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:

Optimized

Now, Let’s optimize this with closures and a little functional magic.

Closure Way

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.

This approach offers a lot of flexibility because that’s not the only thing we can do with them. We can save functions for later execution, combine multiple functions together, and more. And to be honest, this is something you’ll see a lot in JavaScript with the popularity of functional programming. For fun here’s the ES6 version of the createByJob and the JS file:



JavaScript:
/* Closure Example 3 - Creating People For A Company*/
function Person(name, options) {
  this.initialize(name, options);
}
/* Initialization function for creating a single person */
Person.prototype.initialize = function (name, options) {
  this.name = name;
  Object.assign(this, options);
};

/* Normal Way Optimized*/
function createPersonByJob(name, job, options) {
  options.job = job;
  return new Person(name, options);
}

const workersList = [];
workersList.push(
  createPersonByJob('Tim', 'Programmer',{ likes: 'Pasta' }),
  createPersonByJob('Jeena', 'Consultant', { hobby: 'fishing' }),
  createPersonByJob('Tom', 'Programmer',{})
);
console.log(workersList);

/* Closure Way */
/* Creates a person by job with any type of property */
function createByJob(job) {
  return function (name, options) {
    Object.assign(options, { job: job });
    return new Person(name, options);
  };
}
/* ES6 Version */
createByJobES6 = (job) => (name, options) => {
  Object.assign(options, { job: job });
  return new Person(name, options);
};
const programmer = createByJob('Programmer');
const consultant = createByJob('Consultant');

const workerList = [
  programmer('Tim', { likes: 'Pasta' }),
  consultant('Jeena', { hobby: 'Fishing' }),
  programmer('Tom', {})
];
console.log(workerList);
Anyway, I hope this tutorial was helpful and added a new skill to your toolbelt.
 

Users Who Are Viewing This Thread (Users: 0, Guests: 1)

Latest Threads

Latest Profile Posts

One 3-day jam and a Game Awards... this month is moving... \o/
Maker-ing has been being the best thing that happened to me this year so far. it is so good to rescue some old skills fo creativity and the people I have met are really incredible. I love my coffelanders and tocudos buddies. Maybe one day I will reach other countries folks too. S2
Well... My game plays better at 1920x1080, so I guess that's the new resolution. Still runs at 60FPS. :LZSexcite: Also... I really want a boss to be able to build new maps around the player... Mostly because it's visually spectacular! I'm er... not quite sure yet how I can do that without making MV explode.... But I'll find a way, anything in service to the "sparkles"! :kaopride:
How to change your netbooks screen resolution

Forum statistics

Threads
100,795
Messages
979,607
Members
132,437
Latest member
Vollar45
Top