• Empleos
  • Sobre nosotros
  • profesionales
    • Inicio
    • Empleos
    • Cursos y retos
  • empresas
    • Inicio
    • Publicar vacante
    • Nuestro proceso
    • Precios
    • Evaluaciones
    • Nómina
    • Blog
    • Comercial
    • Calculadora de salario

0

261
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 3 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 3 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 Nuestro proceso Comercial
Legal
Términos y condiciones Política de privacidad
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recomiéndame algunas ofertas
Necesito ayuda