Factory functions in JavaScript (Video)

Mattias Petter Johansson
Fun Fun Function
Published in
4 min readSep 14, 2015

Video transcript:

Today, we are talking about Factories. Factories are simply functions that create objects. You can use factories instead of using classes, and factories are simpler than classes and easier to reason about.

This is a weekly show where we try to become more confident and excited about programming by learning intriguing things that we didn’t know before. In order to understand this video, you need to be familiar with closures. If you aren’t sure what closures are, you should watch this earlier episode on that exact topic first.

Before we look at what a factory function looks like, I want to show you a class.

class Dog {
constructor() {
this.sound = 'woof'
}
talk() {
console.log(this.sound)
}
}
const sniffles = new Dog()
sniffles.talk() // Outputs: "woof"

This is a Dog class. It does some setup in it’s constructor — assigns a property to itself called sound. The class also has a method — talk — which uses that sound.

We create a dog, sniffles, which we then call .talk() on, and sniffles promptly tells us “woof”.

This is fine, but there are a couple of annoying things with clasess. If we assign sniffles.talk to something like click handler …

$('button.myButton').click(sniffles.talk)

… things will break, because now the this keyword, inside the talk method, will not be sniffles. It’s going to be something else, probably the DOM element or something. To work around this, you use bind to force this to be sniffles, like this:

$('button.myButton').click(sniffles.talk.bind(sniffles))

This is very common to do, but to be honest, it hurts my gentle beautiful soul to look at it. You can also wrap the talk call in a function, like this:

$('button.myButton').click( _ => sniffles.talk() )

That looks better, but it annoys me that I have to remember to do that at all. It feels like a stupid trap in a shitty computer game. In fact, I think that the concept of this and new in JavaScript feels like that in general. new and this are like some rainbow clown trap that is incredibly unintuitive that you just trip over all the time, and I’m so ashamed of it every time I introduce people to JavaScript.

BUT. You don’t have to use classes. In Java and C# and some other languages, you have to use classes to create objects, but in JavaScript, you don’t. So maybe we can try some other way. Enter, factory functions.

This is the same dog as a factory function:

const dog = () => {
const sound = 'woof'
return {
talk: () => console.log(sound)
}
}
const sniffles = dog()
sniffles.talk() // Outputs: "woof"

Now, dog is simply a function. In it, we create a simple variable, sound, and assign the value “woof” to it. We then return a simple object literal, with one property, talk, a function which logs out the value of sound. Because of the awesomeness of closures, talk has access to the variable sound. A bonus here is that the code outside of the dog doesn’t have access to the sound variable, so it is actually properly private, which is isn’t in the class.

And because we’re not messing around with the this keyword, the reference to sound will always be correct, even when we use talk in the way that broke in the class example:

$('button.myButton').click(sniffles.talk)

I think that for almost all cases, you are better off with factories than classes. Your code will be simpler and easier to reason about.

There is one case where where I think you should be using classes, and that is when you are creating a lot of objects, because classes have bit better performance. But note here, that when I say a lot, I mean a LOT. Using a factory on my computer takes 0.0004 milliseconds, while using a class takes 0.0002 milliseconds. This means that if you are creating 10000 instances, using a class will earn you 2ms over factories, which isn’t going to matter. If you’re creating 10000 objects or less, you should stick to factories. If you’re creating 100 000 instances per second, classes might be for you, but you should really ask yourself if the problem is that you’re creating a hundred thousance instances per second in the first place.

Again, factories are simply functions that create and return objects. We looked at a simple example of how you can use a factory instead of a class, and how it’s less convoluted than a class. We also talked about how classes are a bit faster, but it’s so little that it only matters if you’re creating more than 10000 items per second.

Do you have thoughts or questions? Maybe you even disagree? Good! Post a youtube comment down below, and me or a fellow viewer shall respond to your enquiry.

Again, in this show, we try to become more confident and excited about programming by learning intriguing things that we didn’t know before. New episodes every monday morning, so make sure that you don’t miss the next episode, subscribe to the channel and follow me on twitter @mpjme.

Until next monday — stay curious.

--

--

Mattias Petter Johansson
Fun Fun Function

Creator of Fun Fun Function, a YouTube show about programming.