Skip to content

Instantly share code, notes, and snippets.

@mfdj
Last active September 15, 2020 19:17
Show Gist options
  • Save mfdj/9b89d0302ab4fe32caad471dfb0a461c to your computer and use it in GitHub Desktop.
Save mfdj/9b89d0302ab4fe32caad471dfb0a461c to your computer and use it in GitHub Desktop.
module level static data
const STATE = { counter: 0 };
export { STATE };
import { STATE } from './a.mjs';
export function inc() {
STATE.counter++;
console.log(`inc function sees static as: ${STATE.STATIC}`);
}
import { STATE } from './a.mjs';
import { inc } from './b.mjs';
console.log(STATE); // { counter: 0 }
inc();
console.log(`inc() bumped counter to ${STATE.counter}`);
Object.defineProperty(STATE, "STATIC", {
enumerable: true, // so we can see it in console.log
writable: false,
value: 'my static data'
});
inc();
console.log(`inc() bumped counter to ${STATE.counter}`);
try {
STATE.STATIC = "will throw";
} catch {
console.log("Hey it threw");
}
$ node index.mjs
{ counter: 0 }
inc function sees static as: undefined
inc() bumped counter to 1
inc function sees static as: my static data
inc() bumped counter to 2
Hey it threw
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment