JavaScript Modules (ES 6 Modules) as Singleton Pattern

A counter declared as ES 6 module:


let counter = 0;
export const inc = _ => ++counter;    
is loaded once and therefore can be considered as a singleton.

The first.js:


import { inc } from "./counter.js";
console.log('first',inc());
console.log('first..',inc());

...and another.js modules both are going to access the global counter variable via inc() function:


import { inc } from "./counter.js";
console.log('another',inc());    

The output is:


first 1
first.. 2
another 3    
    

See it in action:

Comments:

Post a Comment:
  • HTML Syntax: NOT allowed
...the last 150 posts
...the last 10 comments
License