简体   繁体   中英

Create a global counter in a NodeJS module

I am trying to create unique ids for my React components. I have created this modules:

var _uid = 0;

function getUid(): {
    ++_uid;
    return `_uid_${_uid}`;
}

export default getUid;

Hoping that the _uid would be increased every time the module function is called, but it is always 1. How can I achieve increase it every time the module is required?

Java script closure helps you there:

    var getUid = (function(){
       var _uid: number = 0;
       return function(){ 
        ++_uid;
        return `_uid_${_uid}`;
       }
    })();

export default getUid;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM