【问题标题】:javascript adding a value to function argumentsjavascript向函数参数添加值
【发布时间】:2011-08-29 23:55:46
【问题描述】:

我正在尝试将参数添加到作为快速 js 路由中的参数传递的函数。

这是一个 expressjs 路由:

app.get('path', someFunc,
function(req, res, next) {
  res.render('layout');
});

其中的函数 someFunc 接受参数 req、res、next。

我想为它添加一个额外的参数。如果我使用 apply 或 call 它似乎会替换所有现有参数。

我希望能够做到:

someFunction (req, res, next, custom) {}

我该怎么做?谢谢。

【问题讨论】:

    标签: javascript node.js arguments express


    【解决方案1】:

    我不确定这是不是最好的方法,但你可以这样做:

    var someFunc = function (req, res, next, custom) { console.log(custom); next(); }
    
    app.get('path', 
    function (req, res, next) { someFunc(req, res, next, 'custom') },
    function(req, res, next) {
        res.render('layout');
    });
    

    【讨论】:

      【解决方案2】:

      我会创建这样的路线:

      // Inside your routes.js:
      module.exports.someRoute = function(myArgument) {
        return function(req, res, next) {
          // Do whatever you want with myArgument.
        };
      };
      
      // Inside your app.js:
      app.get('path', routes.someRoute({ foo: 1 }));
      

      这样你的路线设置就没有任何逻辑了。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-12-18
        相关资源
        最近更新 更多