javascriptobjectfactory-method

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.


Solution

  • 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