“this"原型内部是未定义的

"this" within prototype is undefined

本文关键字:内部 未定义 原型 this quot      更新时间:2023-09-26

我已经花了一个多小时了。

这段代码有什么问题?!

StudentController.js:

function StudentController() {
    this.studentService = {};
};
StudentController.prototype.findAll = function(req, res){
    this.studentService.something();
};
module.exports = StudentController;

app.js

var StudentController = require('./application/StudentController');
var studentController = new StudentController();
app.get('/students', studentController.findAll);

我得到了:

TypeError: Cannot call method 'something' of undefined

为什么"studentService"没有定义??

非常感谢!

你的函数没有在正确的上下文中被调用。

请尝试:

app.get('/students', studentController.findAll.bind(studentController));