Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

167
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda