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

279
Vistas
Is there any way to keep track of how many objects I have created with a factory function in JavaScript?

Let's say I have a factory like this:

const itemFactory = () => {
    const itemName = ''
    const firstMethod = () => {
        // something goes here
    }

    return { itemName, firstMethod }
}

Is there a way I can keep track of how many items I have created with that function? I want to include an index in the itemName property of each item, like this: item0, item1, item2, etc.

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

You can use higher-order function to achieve that:

const createItemFactory = () => {
    let currentItem = 0;
    return () => {
        const itemName = 'item' + currentItem++;
        const firstMethod = () => {
            // something goes here
        }

        return { itemName, firstMethod };
    }
}

you can then create an itemFactory:

const itemFactory = createItemFactory();
const item0 = itemFactory(); 
console.log(item0.itemName); // item0;
const item1 = itemFactory(); 
console.log(item1.itemName); // item1;

Read more about JavaScript closures

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