Digamos que tengo una fábrica como esta:
const itemFactory = () => { const itemName = '' const firstMethod = () => { // something goes here } return { itemName, firstMethod } } ¿Hay alguna manera de hacer un seguimiento de cuántos elementos he creado con esa función? Quiero incluir un índice en la propiedad itemName de cada elemento, así: item0 , item1 , item2 , etc.
Puede usar la función de orden superior para lograr eso:
const createItemFactory = () => { let currentItem = 0; return () => { const itemName = 'item' + currentItem++; const firstMethod = () => { // something goes here } return { itemName, firstMethod }; } } luego puede crear un itemFactory :
const itemFactory = createItemFactory(); const item0 = itemFactory(); console.log(item0.itemName); // item0; const item1 = itemFactory(); console.log(item1.itemName); // item1;