#this reference is not working

9 messages · Page 1 of 1 (latest)

remote pewter
#

export class AuthController {
  constructor(public readonly authService: AuthService) {}

  LoginUser(req: Request, res: Response) {
    console.log("test", this.authService.LoginUser("text"));

    this.authService
      .LoginUser("test")
      .then((result) => res.json(result))
      .catch((error) => console.log(error));
  }

  RegisterUser(req: Request, res: Response) {
    res.json("Auth Register");
  }
}

``` why this code doesn't work for loginUser but when i do a arrow function "this" gets the reference?
rose ingot
#

if you dereference the method, the binding gets lost. what method is having the issue exactly?

#

(btw, in ts, methods are in camelCase by convention, rather than PascalCase, just in case you weren't aware)

bitter hearth
#

this in a method is the object that the method was called on. So

const ac = new AuthController
ac.LoginUser() // this is ac
const loginUser = ac.LoginUser
logicUser() // this is null or something like that
const obj = {
  loginUser: ac.LoginUser
}
obj.loginUser() // this is obj
#

If you use an arrow function instead then it keeps this as the instance it was created in, no matter what. (This is largely we have => functions, it's not just syntax shortcut)

remote pewter
#

!resolve

#

!resolved