I'm aware that the subject of "this" in both JS and TS has been covered by many questions, but I haven't been able to find an answer to the specific issue I'm facing. I'm certain that I'm just not understanding something basic and it's tricky to google for amongst the mountain of questions that boil down to arrow function scoping rules.
To preface, the code I'm struggling with is running on a Node back-end.
So, I've created a controller class with a method defined not as an arrow function (simplified for demonstration):
class UserController extends AbstractController {
constructor() { ... }
public async getUsers(x, y): Promise<any> {
return this.processRequest( ... ); //processRequest is a protected async definition on AbstractController
}
}
// ...
export default new UserController()
The issue I'm having is that this
inside getUsers()
is undefined
, where I'd naturally expect it to be the instance of UserController
it's executed on.
If I do convert getUsers
to an arrow function...
class... {
public getUsers = async (x, y): Promise<any> => {
return this.processRequest( ... );
}
}
...then it works as expected.
I believe I understand how arrow function this
captures work with regards to the surrounding scope; but in this case I feel like I'm missing two key understandings:
- why does the first method not have any
this
? I feel likethis
should be the instance ofUserController
, and if not then at least it should be some more global object. - why does the second method work at all? There is no "surrounding scope" to capture
this
from - is there?
Here's how getUsers()
is called:
import UserController from 'user.controller';
userRouter.get('/', authMiddleWare, UserController.getUsers);