Classes are not always better. It really depends upon the circumstances. Each has their place in your programming toolset.
A class has the following advantages:
- There's defined syntax in the language
- You can sub-class a class to extend it
- You can more easily have many properties and many methods.
- Methods are automatically non-enumerable and run in strict mode.
- The syntax in the code that uses a class somewhat self-describes what is happening since
new countPlusClass()
makes it clear you're creating an object that will then have methods and probably state. That's not as obvious with the closure you show.
- For object with a lot of methods there's some space-savings benefit to the prototype that a
class
uses.
- Developer tools will recognize an instance of a class and know how to display it, auto-complete when typing code for it, how to represent it in the debugger, how to use it in error messages, etc...
A closure has these advantages:
- The data in the closure is complete private. Nobody can get to it from outside the closure.
- In some circumstances, the caller may find it takes less code to use the closure since you make one function call (sometimes passing arguments) and you get back another function that then implements the one thing this is supposed to do (your mention of middleware comes to mind).
So, I'd say that if you want or need or value any of the benefits of the class, then use the class.
If you don't want or need any of the benefits of the class and the simpler interface of the closure meets your needs or if you really need the privacy of the closure, then you can choose the closure.
I'd say that for a given circumstance, one of these tools may be a better "fit" for the problem at hand.
As has been mentioned in the comments, you can also have factory functions that may be closures (retain private state in a closure) and may return an object with methods and/or properties that can even be an object created by instantiating a class. So, these concepts can all be combined too to get some of the benefits of both.