Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Nodejs: express call class method return undefined `this`

This is my code:

bannerController:

class bannerController extends generalController {
  constructor() {
    super(BannerService);
  }
}

export default new bannerController();

generalController:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

export default class generalController {
  public service: any;

  constructor(service: any) {
    this.service = service;
  }

  public async status(req: Request, _res: Response, next: NextFunction): Promise<void> 
  {
    console.log(this)
  }
}

router:

router.patch(
  '/banner/:id/status',
  bannerController.status,
);

This line console.log(this) return undefined

If I change it to bannerController.status.bind(bannerController) work fine.

But I don’t want to use call, bind and …

>Solution :

An alternative approach would be giving your class a method that returns the middleware function, as illustrated by the following code (Javascript, not Typescript, sorry):

class generalController {
  ...
  statusMiddleware() {
    return async function(req, _res, next) {
      console.log(this);
    }.bind(this);
  }
}
router.patch(
  '/banner/:id/status',
  bannerController.statusMiddleware()
);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading