admin管理员组

文章数量:1327698

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 autopletion on methods (e.g "model" in mongoose) (at least it doesn't show the annoying yellow underline that says "Unresolved function or method"

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 autopletion on methods (e.g "model" in mongoose) (at least it doesn't show the annoying yellow underline that says "Unresolved function or method"

Share Improve this question edited Apr 16, 2014 at 14:59 arg20 asked Apr 16, 2014 at 14:44 arg20arg20 4,9911 gold badge53 silver badges75 bronze badges 3
  • Relevant, possible dupe stackoverflow./questions/14134004/… – Trufa Commented Apr 16, 2014 at 14:52
  • Trufa I read that question, and I thought it was more specific than mine. I simply want to know if adding the keyword "new" in any scenario makes no difference, that's all. – arg20 Commented Apr 16, 2014 at 14:59
  • @arg20 did you find another workaround to this IntelliJ/Webstorm issue? – awidgery Commented Apr 29, 2016 at 11:21
Add a ment  | 

2 Answers 2

Reset to default 5

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.

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.

本文标签: javascriptNodejs new require()Stack Overflow