CodePark/ questions / this in methods & callbacks
START PRACTICINGPRACTICE
Backend question · Object-oriented programming › this in methods & callbacks

A request to GET /users fails. What is the error?

class UserService {
  constructor(repo) { this.repo = repo; }
  list() { return this.repo.findAll(); }
}
const service = new UserService(userRepo);
app.get("/users", service.list);
TypeError: Cannot read properties of undefined (reading 'repo')

The error is Cannot read properties of undefined (reading 'repo'). service.list passes only the function. The object is not attached. Express later calls it as a plain function, so this is undefined. Class bodies always run in strict mode, so this is not the global object.

"
ReferenceError: repo is not defined" is wrong. The code reads this.repo, a property lookup, not a variable. The lookup fails because this itself is undefined.