CommonJS模块-导出返回带有参数的函数的函数 [英] CommonJS Modules - Exporting a function that returns a function with arguments
问题描述
在此 rendr-会话例如,有一个快速的中间件模块...
In this rendr - sessions example, there's an express middleware module...
module.exports = function incrementCounter() {
return function incrementCounter(req, res, next) {
var app = req.rendrApp
, count = app.get('session').count || 0;
req.updateSession('count', count + 1);
next();
};
};
您不能通过以下操作来实现同一目标吗?
Can you not achieve the same thing with the following?
module.exports = function incrementCounter(req, res, next) {
var app = req.rendrAp
, count = app.get('session').count || 0;
req.updateSession('count', count + 1);
next();
};
我的问题是,为什么要导出一个返回带有参数的函数?
My Question is, why would you export a function which returns a function with arguments? Is there some sort of benefit to the former that I am unaware of?
推荐答案
rendr使用Express风格的中间件。
rendr uses Express-style middleware.
按照惯例,Express中的第三方中间件不作为实际的中间件提供。而是将它们作为基于选项对象参数创建中间件的函数提供。
By convention, third-party middleware in Express are not provided as the actual middleware. Instead, they are provided as functions that create the middleware based on an options object parameter.
但是,由于此处未提供任何选项,因此将其省略。
However, since there are no options to be provided here, it is omitted.
但是,在为了遵循周围库的约定,它必须是一个返回中间件函数的工厂函数。所以这就是为什么在这里将其包裹起来的原因。
But still, in order to follow the conventions of the surrounding library, it needs to be a factory function that returns a middleware function. So that's why it is wrapped up that way here.
这篇关于CommonJS模块-导出返回带有参数的函数的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!