简体   繁体   中英

Persistent state in typescript module

I would like to do something like this:

let serialId = 0;

export function getId() {
    serialId = serialId + 1;
    return serialId;
}

And every time I call it from various places id would increment. Now it seems that serialId value is independent for every import .

Do I need some magical declaration or maybe even some tool to have persistent "global" state. I don't want serialId to be visible outside of module if possible.

If you prefer more functional way, you can export factory:

export const stateFactory = (() => {
  let id = 0;
  return ({
    getId() {
        return ++id;
    }
  })
})()

const b = stateFactory.getId(); // 1
const c = stateFactory.getId(); // 2

You can try with methods in a class:

 export default class { serialId: number; constructor () { this.serialId = 0; } public getId(): number { this.serialId += 1; return this.serialId } } 

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