NodeJS modules vs classes
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.
W开发者_如何学JAVAhat 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.
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.
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
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.
精彩评论