Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NodeJS modules vs classes

Tags:

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.

like image 338
Tower Avatar asked Aug 02 '11 15:08

Tower


People also ask

What are Nodejs modules?

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.

What is the difference between class and module in JavaScript?

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.

What is difference between module and package in node JS?

A package in Node.js contains all the files you need for a module. Modules are JavaScript libraries you can include in your project.

Are there classes in Nodejs?

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.


1 Answers

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.

like image 195
Jeremy Roman Avatar answered Sep 27 '22 19:09

Jeremy Roman