[英]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. 每次我从不同地方调用它时,id都会增加。 Now it seems that serialId
value is independent for every import
. 现在看来serialId
值对于每个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. 我不希望serialId在模块外部可见。
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 } }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.