Many questions have addressed the topic of "this" in both JS and TS, but I have not been able to find a solution to my specific problem. It seems like I might be missing something fundamental, and it's difficult to search for an answer amidst the sea of inquiries related to arrow function scoping rules.
Just to provide some context, the code causing me trouble is running on a Node back-end.
So, I have a controller class with a method not defined 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 problem I'm encountering is that this
inside getUsers()
is undefined
, whereas I would expect it to be the instance of UserController
on which it is being executed.
If I were to convert getUsers
to an arrow function...
class... {
public getUsers = async (x, y): Promise<any> => {
return this.processRequest( ... );
}
}
...then it behaves as anticipated.
I comprehend how arrow function this
captures work in terms of the surrounding scope, but in this scenario, I sense that there are two crucial concepts that are eluding me:
- Why does the initial method lack any
this
? I believethis
should refer to the instance ofUserController
, or at the very least, it should point to some broader object. - Why does the second method function at all? There doesn't seem to be a "surrounding scope" from which to capture
this
- or is there?
Here's how getUsers()
is being invoked:
import UserController from 'user.controller';
userRouter.get('/', authMiddleWare, UserController.getUsers);