Home > Net >  How does the private keyword let us both declare and initialize a class instance?
How does the private keyword let us both declare and initialize a class instance?

Time:06-01

I'm reading the Nest.js documentation, and there is a line that I don't quite understand.

We customize our CatsController using its constructor function, so when the IoC container creates the catsController instance, it is created with a catsService instance as a constructor parameter. At least this is my best guess based on the whole document. But what does the following exactly mean:

Notice the use of the private syntax. This shorthand allows us to both declare and initialize the catsService member immediately in the same location.

Why does the private keyword achieve that? How would it look if we did not use the shorthand syntax?

CodePudding user response:

The initialization of the CatsService is done by Nest.js in both cases, that's one of the key premises of the IoC it relies on. The usage of the private keyword in constructor declaration is completely optional, and is useful for making the constructor parameter an attribute of CatsController during its initialization. Without it, you should write:

@Controller('cats')
export class CatsController {
  private catsService: CatsService;
  
  constructor(service: CatsService) {
    this.catsService = service;
  }
  /* TODO */
}

Look at how the private keyword comes in place to declare the catsService as a private attribute of the class, and if we were to use it inside the constructor parameter declaration it would have the same meaning, resulting in a smaller and simpler code. Lastly, this is a syntactic feature of Typescript, and has no relation with NestJS or DI.

  • Related