1

I'm trying to figure out a concept in typescript that I can't find the wording for to google online

using express with typescript

login route

import express, { Request, Response } from "express";
import LoginController from "../controllers/login.controller";
const router = express.Router();
const loginController = new LoginController();
router.post("/", loginController.login);
router.post("/", (req: Request, res: Response) => loginController.login(req, res));

export default router;

as you can see, there are two routes for the same path - but this is just for my question: the first post to ("/") has "this" in the logincontroller class undefined the second one works perfectly

import Cache from "../services/Cache";
class LoginController {
    cache: Cache = Cache.getInstance();

    constructor() {
        this.cache = Cache.getInstance();
    }

    public async login(req: Request, res: Response) {
        if (req.body.username === "admin" && req.body.password === "Aa123123") {
            console.log("trying to access cache'");
            const access_token = await this.cache.get("access_token", () => {
                return "a_A1S2D3";
            });
            console.log("got access token");
            res.send({ status: true, data: access_token, msg: "Logged in successfully" });
        } else {
            res.send({ status: false, data: null, msg: "User not found" });
        }
    }
}

export default LoginController;

this is the function.

What I am trying to understand is why

router.post("/", loginController.login);

does not have a "this" instance and the second syntax does - cause the "this" should be bound by the class itself, shouldn't it?

Liad Goren
  • 299
  • 1
  • 4
  • 18
  • For regular functions, the value of "this" is determined by how the function is called. If you call the function using the code `loginController.login(req, res)` like in example 2, then the characters `loginController.` are telling javascript/typescript to set `this` equal to `login`. But if you just pass a function into router.post, then you're not the one that calls the function; router.post is. And it has no idea what you want `this` to be equal to, so it will call your function without any context, making `this` undefined (in strict mode) – Nicholas Tower Aug 01 '22 at 08:56

0 Answers0