Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

282
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!