Expressjs。 从原型函数调用构造函数中的函数时,TypeError

我试图从原型调用构造函数中的函数,但不断得到下面的错误,我不知道什么是我的代码错了。

TypeError: this.authorize is not a function 

这是我的代码:controller.js

 var Controller = function() { this.authorize = function(req, res) { if (!req.user) { res.redirect("/"); } }; }; Controller.prototype.online = function(req, res) { this.authorize(req, res); res.render('./play/online'); }; var controller = new Controller(); module.exports = controller; 

route.js

 var router = require('express').Router(); var controller = require('../controller'); router.get('/online', controller.online); module.exports = router; 

如果我把控制器之外的授权function,然后我可以打电话,但我不想这样做。 那我能做什么?

更新:
这个错误发生在Nodejs中,当我应用请求“/在线”,而不是纯Javascript

作为callbackonline上传时,您正在放弃上下文

 router.get('/online', controller.online.bind(controller)); 

或者在构造函数中

 var Controller = function() { this.authorize = function(req) { console.log(req); }; this.online = this.online.bind(this); }; 

像在线function一样,在Controller的原型上设置授权function。

编辑:我testing了你的代码(不使用Controller.prototype),它适用于我…

我可以在在线function中调用授权。 从联机function中调用授权还是在其他地方发生错误? 你确定你的代码中没有错别字吗?

你可以尝试在构造函数中定义你的在线函数吗?

 //Your initial version: works for me... var Controller = function() { this.authorize = function(req) { console.log(req); }; }; Controller.prototype.online = function(text) { this.authorize(text); }; var controller = new Controller(); controller.online("Some text"); //My prototype version: works as well... var Controller2 = function() {}; Controller2.prototype.authorize = function(req) { console.log(req); }; Controller2.prototype.online = function(text) { this.authorize(text); }; var controller2 = new Controller2(); controller2.online("Some text2");