NodeJS应用程序布局和variables传递

嗨,大家好我有一个应用程序布局小问题。 我正在像这样设置我的控制器。

ApplicationController = function(_app) { this.app = _app; console.log(this.app); //this works }; ApplicationController.prototype.index = function(req, res, next) { console.log(this.app); //this is undefined res.json("hello"); }; module.exports = function(app) { return new ApplicationController(app); }; 

而在我的路线文件,我正在这样做。

 module.exports = function(app) { //require controllers var Application = require('./controllers/ApplicationController')(app); //define routes app.get('/', Application.index); app.get('/blah', Application.blah); return app; }; 

我传递的应用程序variables不显示在其他实例方法中。 有没有这个原因,我失踪了? 谢谢你的帮助。

在过去,我把控制器设置成这样。

 module.exports = function(app) { var controller = { //app is defined res.render('index', { title: "Index" }); } }; return controller; }; 

但是我更喜欢这个其他的模式,所以我更加好奇它为什么不起作用。

尝试改变这些行:

 app.get('/', Application.index); app.get('/blah', Application.blah); 

至:

 app.get('/', Application.index.bind(Application)); app.get('/blah', Application.blah.bind(Application)); 

否则,您的路由不会在您的Application实例的上下文中被调用。