在路由中使用类expression

我决定从函数到类重写代码。 但是,我遇到了这样一个问题,我的这个undefined

路由

// router.js const ExampleController = require('./ExampleController'); const instanceOfExampleController = new ExampleController(); // Require express and other dependencies app.post('/post-to-login', instanceOfExampleController.login) // An error appears inside the method 

和控制器

 // My Controller class ExampleController { // Private method myPrivateMethod(info) { return info.toUpperCase(); } login(req, res, next) { console.log('----------------------'); console.log(this); // Here "this" equal of undefined! console.log('----------------------'); const someValue = this.myPrivateMethod(req.body.info); // Not work! res.send(someValue); }; } 

instanceOfExampleController.login.bind(instanceOfExampleController)将做的伎俩。 一旦被直接调用,函数就会丢失它的上下文。

或者,您可以使用:

 app.post('/post-to-login', function (req, res, next) { instanceOfExampleController.login(req, res, next); });