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

286
Visualizações
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 Respostas
Responde à pergunta

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 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