Thursday, 11 May 2017

Best way to use modules in NodeJS methods vs global

I am trying to understand and find out the better way to use modules in node js that are imported via require.

Here are two possible ways I've found.

class BookManager {
    constructor() {
        this._validator = require('validator');
        this._BookModel = require('api/book').BookModel;
        this.createNewBook = this.createNewBook.bind(this);
    }
}

And

const validator = require('validator');
const BookModel = require('api/book').BookModel;
class BookManager {
    constructor() {
        this.createNewBook = this.createNewBook.bind(this);
    }
}

In the first case we are encapsulating all neccessary objects as members of the class. From my previous experience working with other languages, this could probably replaced with the dependency injection via constructor.

But I am not sure in case of Node JS which way is preferable and why.

Could someone explain the differences, especially about scopes.

thanks.



via e109848

No comments:

Post a Comment