arg20
arg20

Reputation: 4991

Nodejs new require()

Are these two lines the same?

var myModule = new require('my-module')

and:

var myModule = require('my-module')

The former helps intelliJ Idea (or Webstorm) to do autocompletion on methods (e.g "model" in mongoose) (at least it doesn't show the annoying yellow underline that says "Unresolved function or method"

Upvotes: 5

Views: 2494

Answers (2)

Jason
Jason

Reputation: 13766

Instantiating what is returned by require.

new should be used when you're instantiating a new instance of a class or function, and not otherwise. You almost certainly don't want to instantiate an instance of require.

However, if you want to instantiate an instance of a class/function returned by require, you could probably do something like:

var myModuleInstance = new (require('my-module'));

The extra containing parentheses means you're instantiating the returned object, not directly instantiating require.

Upvotes: 5

Matt
Matt

Reputation: 75317

In terms of JavaScript, they're not the same. In terms of require() as a function? It seems so, but I'd still advise against doing it.

Using new does a lot under the hood. require() will be affected by the use of new, as it's internal value of this will change.

var foo = {
    path: '/foo/bar/',

    require: function (module) {
        console.log(this.path + module);
    }
};

foo.require('baz'); // logs /foo/bar/baz
new foo.require('trev'); // logs undefinedtrev

Currently require() seems not to use this at all (as it's behaviour doesn't change whether you change the value of this or not). However, this isn't guaranteed to be the case in the future; it isn't documented.

TL;DR: don't use it.

Upvotes: 4

Related Questions