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

Expressjs. TypeError when call function in constructor from prototype function

我试图从原型调用构造函数中的一个函数,但一直出现以下错误,我不知道我的代码有什么问题。

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;

如果我将授权函数放在 Controller 之外,那么我可以调用它,但我不想那样做。 那我该怎么办?

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

像在线功能一样在控制器原型上设置授权功能。

编辑: 我测试了您的代码(未使用 Controller.prototype)并且对我有效...

我可以在在线功能中调用授权。错误是在线功能调用授权时发生的还是其他地方发生的?您确定您的代码中没有错字吗?

您能否尝试在构造函数中也定义您的在线函数?

//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");

您在将 online 作为回调传递时丢失了上下文

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

或构造函数内部

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

    this.online = this.online.bind(this);
};