Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should use Class or Module in NodeJS

I'm newbie on NodeJS. I'm researching about the inheritance on NodeJS and found there's an inheritance using Class (on ES6). I have some questions about the using of the Class and Module to decide which one should be used in my case:

  1. As I know, "Module" is cached after i run once, it means I don't need to initial every time, and for "Class" which i need to initial every time I use it. So does it make a leak memory or not good for performance?
  2. In my case, i would like to implement the inheritance for some common functions, then i can reuse them in my child. In case using "Class": If there are multiple request sent from Client side at the same time, does it affect to the Server's performance such as the slower's response or anything?
  3. If using "CLASS", can I trigger ONCE for a global function( Any other inheritance classes will not trigger that function.)
  4. After create an instance of Class and processing the functionality, will it be released?

Thanks in advance.

like image 927
HTKT89 Avatar asked Jun 23 '18 17:06

HTKT89


1 Answers

Should use Class or Module in NodeJS

This is a false choice. You may well use both. You certainly want to use modules (in fact, it would be very hard not to). You may or may not want to use class (more in this question's answers), and if you don't you may or may not want to use pseudo-classical inheritance; or you might prefer to directly use prototypical inheritance. That's a style choice.

1. As I know, "Module" is cached after i run once...

Yes, modules are cached. You use the inline code of a module to do its initialization. Then the module exports functions and/or constructor functions (loosely, "classes"), etc., that other modules can use.

2. ... If there are multiple request sent from Client side at the same time, does it affect to the Server's performance such as the slower's response or anything?

Creating objects, including creating objects via constructor functions, is very fast. Worry about functionality and maintainability. Worry about performance if and when there's a problem.

3. If using "CLASS", can I trigger ONCE for a global function( Any other inheritance classes will not trigger that function.)

You can create a single instance of a class and export it from a module for reuse without being re-created, yes.

4. After create an instance of Class and processing the functionality, will it be released?

If nothing keeps a reference to an object, the object is eligible for garbage collection, yes. Naturally, if something keeps a reference to the object (for instance, if you export it from a module), it isn't eligible for garbage collection.

like image 182
T.J. Crowder Avatar answered Sep 17 '22 16:09

T.J. Crowder