简体   繁体   English

新的require('下划线')vs require('下划线')NodeJS [Webstorm 7自动完成]

[英]new require('underscore') vs require('underscore') NodeJS [Webstorm 7 autocomplete]

In some app.js, using the following code 在某些app.js中,使用以下代码

var _ = require('underscore');

_.times(2, function() {
  console.log('Hello');
});

Webstorm 7 complains about unresolved function 'times'. Webstorm 7抱怨未解决的功能“时间”。 After some googling I found out that if I do a var _ = new require('underscore'); 经过一番谷歌搜索后,我发现如果我做var _ = new require('underscore'); then webstorm doesn't complain at all. 那么webstorm根本不会抱怨。 However, I am very very new to NodeJS so couldn't grasp this properly. 但是,我对NodeJS非常陌生,因此无法正确掌握这一点。

Please tell me what is the difference between new require('') and require('') and how exactly it solved the issue. 请告诉我new require('')require('')之间有什么区别,以及它如何解决该问题。 Also, are there performance implications of using new require ? 另外,使用new require是否会对性能产生影响?

To make things clear: _ is a function, so you can use it with new keyword. 需要说明的是: _是一个函数,因此可以将其与new关键字一起使用。 But this is supposed to be used as wrapper, which adds methods to object you pass in order to make your api object oriented. 但这应该用作包装器,它为您传递的对象添加方法以使api对象面向。

So if you use _ as a function or constructor you need to pass an object as an argument, and you'll get object with your data and some of underscore's functions attached as methods (that is, you don't need to pass your data as a first argument, it is incapsulated in object). 因此,如果将_用作函数或构造函数,则需要将一个对象作为参数传递,并且将获得带有数据的对象以及作为方法附加的下划线的某些函数(也就是说,您不需要传递数据作为第一个参数,它封装在object中)。

Basically, writing var _ = new require('underscore') is incorrect. 基本上,编写var _ = new require('underscore')是不正确的。 You will get useless object, which definitely not real _ . 您将获得无用的对象,它绝对不是真实的_ And what about Webstorm - it will complain a lot, unless you turn these features off. 而Webstorm呢-除非您关闭这些功能,否则它会抱怨很多。 Javascript is too dynamic to make them work in all cases. Javascript太动态了,无法在所有情况下都能正常工作。

Summary: use var _ = require('underscore'); 摘要:使用var _ = require('underscore'); , ignore Webstrom. ,请忽略Webstrom。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM