要求中的双括号是什么意思 [英] What does double parentheses mean in a require
问题描述
我知道这个 require 语句的作用.
I know what this require statement does.
var express = require('express');
var app = express();
但有时我会在 require 之后看到两个括号.
But sometimes i have seen two parentheses after the require.
var routes = require('./routes')(app);
问)这是什么意思,它是如何工作的?
Q) What does this mean, and how does it work?
推荐答案
这是一种模式,其中 module.exports
您需要的模块被设置为一个函数.要求该模块返回一个函数,并且 require 后面的括号用参数对函数求值.
This is a pattern in which the module.exports
of the module you are requiring is set to a function. Requiring that module returns a function, and the parentheses after the require evaluates the function with an argument.
在上面的示例中,您的 ./routes/index.js
文件将类似于以下内容:
In your example above, your ./routes/index.js
file would look something like the following:
module.exports = function(app) {
app.get('/', function(req, res) {
});
// ...
};
这种模式通常用于将变量传递给模块,如上面的 app
变量所示.
This pattern is often used to pass variables to modules, as can bee seen above with the app
variable.
这篇关于要求中的双括号是什么意思的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!