-1
在node.js项目中,我看到require(path)和require(path)()是什么引起额外的paranthasis。 什么时候应该使用require(path)并且require(path)()node.js中的require(path)和require(path)()有什么区别
在node.js项目中,我看到require(path)和require(path)()是什么引起额外的paranthasis。 什么时候应该使用require(path)并且require(path)()node.js中的require(path)和require(path)()有什么区别
require()
statement从正在加载的模块中返回module.exports
属性。你所做的完全取决于模块设置的内容。
如果模块将其设置为某种(通常称为模块构造函数)的函数,那么很自然的与var something = require('xxx')(...);
叫它但是,如果模块只是出口对象具有的属性就可以了,那么尝试调用它实际上是一个编程错误。
那么,它完全取决于你正在加载的模块是在输出。
例如,加载文件系统模块时,这纯粹是:
var fs = require('fs');
在这种情况下,变量fs
只是一个对象(不是函数),所以你不会把它 - 你只是引用它的属性:
fs.rename(...)
这里有一个模块的出口为例一个构造函数,你会后与()
拨打:
// myRoutes.js
module.exports = function(app) {
app.get("/", function() {...});
app.get("/login", function() {...});
}
// app.js
// other code that sets up the app object
// ....
// load a set of routes and pass the app object to the constructor
require('./myRoutes')(app);
而且,这里有一个模块只导出属性,这样你就不会调用模块本身就是一个例子:
// myRoutes.js
module.exports.init = function(app) {
app.get("/", function() {...});
app.get("/login", function() {...});
}
// export commonly used helper function
module.exports.checkPath = function(path) {
// ....
}
// app.js
// other code that sets up the app object
// ....
// load a set of routes and then initialize the routes
var routeStuff = require('./myRoutes');
routeStuff.init(app);
if (routeStuff.checkPath(somePath)) {
// ...
}
()是调用一般编程方法。 –