Andreszl Andreszl - 3 years ago 238
Node.js Question

Classes vs modules in nodejs

My question is if it is better the use classes in nodejs or the function or prototypes and modules, i know that most use the modules and function prototypes, but which is better?

And we most consider that classes have always been in all programming languages the best option to work.

Thank you in advance

Answer Source

My question is if it is better the use classes in nodejs or the function or prototypes and modules, i know that most use the modules and function prototypes, but which is better?

Your question seems a bit misguided. In node.js, one does not choose between classes, prototypes and modules.

First off classes in Javascript uses the prototype. The class syntax is just syntactical sugar for defining a constructor and methods on the prototype. When you use the class syntax, you are creating a constructor with a prototype and causing methods to be added to the prototype (under the covers). So, there is no tradeoff between using classes and using the prototype.

The only tradeoff there is there is between using the new class syntax to define your prototype vs. doing it the older, manual way.

Then, classes are pretty much orthogonal to modules. You use modules when you want to encapsulate a body of code in a module interface so you can reap all the benefits of using modules (easier sharing, reuse, documenting, testing, etc...). That module interface can be whatever you think is most appropriate for your circumstance. You can export a series of plain functions. You can export one or more object constructors. You can export factory functions that create objects for you that you can then use methods on. The module scheme is massively flexible so you can export pretty much any type of interface you want (and classes can be a part of that if you choose).

There is no "best" way to export things from modules because it depends upon your needs, your chosen architectural and coding style, etc...

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download