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:

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()
);

Leave a Reply