Monday, 30 July 2018

closures

Closures are great! When I first started coding in javascript I wondered how you manage to hide data in your objects... The answer closures!!

Let's take a normal class (oh thanks ES6!)

Now how would we do the same with a closure?

the factory function serves to store all the information inside of its closure when it is executed, so all passed in parameters are available to any functions on the created object. It also makes them inaccessible to anything on the outside. Elegant and simple, no extra syntax required.

After using this pattern for a while in some applications I noticed that we were often only returning a method with a single function attached to it, in these cases is it even necessary to have the object?

In this example, we just return a function that can do the work. This is simpler and it also helps to make it so that the abstraction only performs a single task.

No comments:

Post a comment