To me classes are quite similar to NodeJS (CommonJS) modules. You can have many of them, they can be reused, they can use each other and they are generally one-per-file.
What makes modules so different from classes? The way you use them differs, and the namespace difference is obvious. Besides that they seem very much the same thing to me or perhaps I am just not seeing the obvious benefit here.
In Node. js, Modules are the blocks of encapsulated code that communicates with an external application on the basis of their related functionality. Modules can be a single file or a collection of multiples files/folders.
Classes were introduced as a way to expand on prototype-based inheritance by adding some object oriented concepts. Modules were introduced as a way to organize multiple code files in JavaScript and expand on code reusability and scoping among files.
A package in Node.js contains all the files you need for a module. Modules are JavaScript libraries you can include in your project.
Lots of people don't know it, but you can use and extend real classes in Node. js already. There's a few drawbacks, but once you learn about them, they're really not drawbacks but postive things, that will make your code faster and better.
Modules are more like packages (to use the Java term) than classes. You don't instantiate a module; there is only one copy of it. It's a tool for organizing related functionality, but it doesn't typically encapsulate the data of a particular instance of an object.
Probably the closest analogue to a class (setting aside those libraries that actually construct class-based inheritance in JavaScript) is just a constructor function. You can of course put such functions inside a module.
function Car() { this.colour = 'red'; } Car.prototype.getColour = function() { return this.colour; }; var myCar = new Car(); myCar.getColour(); // returns 'red'
You use both modules and classes for encapsulation, but the nature of that encapsulation is different.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With