NodeJS modules vs classes

2019-03-23 05:21发布

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.

3条回答
再贱就再见
2楼-- · 2019-03-23 05:52

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.

查看更多
闹够了就滚
3楼-- · 2019-03-23 05:52

JS was initially a prototypal inheritance system. It was super simple like the rest of the language. But then Netscape decided to make it be more like Java and added the idea of constructors to the language. Hence pseudo classes were born. You can check this link to know how prototypal OOP is used in JS: http://howtonode.org/prototypical-inheritance

查看更多
我命由我不由天
4楼-- · 2019-03-23 05:58

One critical thing; that "generally one-per-file" thing is not true; modules are absolutely one-per-file. A require() that brings the module's exports into the namespace has no way of distinguishing between the exported contents of that module; everything that module (file) exports are imported with a require() statement. Attempting to put more than one module into a file only means that you'll get everything in that file when you try to load "either" module.

查看更多
登录 后发表回答