Search code examples
javascriptnode.jsrequirejses6-class

Is using es6 class in node.js useful?


I just wondering while working on node.js projects. Should I declare a class in a function, to use it for example globally like let task = new Task(params);?

I'm thinking about two different ways, to handle classes

Case: no class

'use strict'

/**
 *
 * @param taskId
 * @param timeStamp
 * @constructor
 *
 */
function task(taskId, timeStamp) {

  this.taskId = taskId;
  this.timeStamp = timeStamp;
}

/**
 *
 * type {task}
 *
 */
module.exports = task;

I'm requiring task.js as let task = require('./task.js'); somewhere. For example in globals.js, witch is required as let g in app.js.

Anyway, it's working like a charm, to create somewhere else a new Task like I wrote above: let task = new g.task('someTaskId', varForTStamp);


Case: class

'use strict'

/**
 *
 * @constructor
 *
 */
function task() {

  class Task {
    
    /**
     *
     * @param taskId
     * @param timeStamp
     */
     constructor(taskId, timeStamp) {

       this.taskId = taskId;
       this.timeStamp = timeStamp;
     }

     //in task is no get or set method needed
   }

/**
 *
 * type {task}
 *
 */
 module.exports = task;

Same thing here. Call somewhere else a new Task by using the same requires and definitions.

Do I have to declare a class if I have to work with get() and set() methods? Not even if I need to work with get() and set(), I have to use class. It would work the same way like in class. Both ways working good and there are no problems or exceptions.

But what is happened in the background of requireJS, node.js? Should I use a certain technique, to write clear code for better performance?

Is there a better way to handle new objects across a node.js project? How do you manage it and handle with that kind of differences?


Solution

  • You usually do not need to return a class from a function (your second code snippet). You can just directly export the class.

    This is probably the best way to do it:

    test.js:

    class Test{
      constructor(info){
        this._info=info;
      }
    
      getInfo(){
        return this._info;
      }
    }
    
    module.exports=Test;
    

    main.js:

    const Test=require('./test');
    const myTest=new Test("hello");
    const myOtherTest=new Test("world");
    console.log(myTest.getInfo());
    console.log(myOtherTest.getInfo());
    

    Also you should not have to use a global.js file. For example instead of doing

    const g=require('./global');
    const myTest=new g.Test("abc");
    

    You should directly require Test:

    const Test=require('./test');
    const myTest=new Test("abc");