Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

166
Visualizações
How does the private keyword let us both declare and initialize a class instance?

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?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

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.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda