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
2 Answers
Reset to default 5Instantiating 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
版权声明:本文标题:javascript - Nodejs new require() - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742226722a2436455.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论