1

Routes.js includes the following lines of code:

X = {};
X.xFunction(user) { 
  // some code here 
  // console.log(user.Name);
}       
var Router_Functions = require('/Router_Functions');

app.get('/', Router_Functions.aFunction)

Router_Functions.js

exports.afunction = function (req, res) {

   xFunction(req.session.user);

}

Here, error is xFunction is undefined. But in such case, how do you to pass function X.xFunction() from 'routes.js' to 'Router_Functions.js'

4

2 回答 2

2

你的架构有问题。这样的做法有点不对。如果您需要一个模块中定义的函数存在于另一个模块中,那么您必须将其导出到单独的文件中。IE:

// xFunction module
var X = {};
X.xFunction(user) { 
  // some code here 
  // console.log(user.Name);
}
module.exports = X;

然后在 *Router_Functions.js*

exports.afunction = function (req, res) {

   var X= require("xFunction.js");
   X.xFunction(req.session.user);

}

如果你真的想在Routes.js中定义函数,那么你必须以某种方式传递它。例如作为aFunction的参数

app.get('/', function(req, res, next) {
   Router_Functions.aFunction(req, res, xFunction);
});

// Router_Functions.js
exports.aFunction = function (req, res, xFunction) {
   xFunction(req.session.user);
}
于 2013-09-08T17:14:21.017 回答
-1

你必须在调用像 Router_Functions.aFunction(X.xFunction(user)) 这样的 aFunction 时通过 xFunction

于 2013-09-08T11:35:29.557 回答