Caleb Anthony Caleb Anthony - 3 months ago 10
Javascript Question

How can I create a variable that can be edited in other modules without being global?

I'm developing a game and I have a global

save
variable that holds the various aspects of the game (units, upgrades, etc). The game code is separated into several modules, such as upgrades or achievements.

How can I make the
save
variable accessible in the other modules? Importing gives me a read-only copy of the variable, which is not useful. How can I share the variable with the other modules without making it global?

I'm not looking for the easiest solution to the problem, I'm looking for best practices.

EDIT: I'm using ES6 import/export functionality.

Answer

Importing may give you a read-only copy of the variable, but an imported object is not immutable. Therefore, if you want to share a state object of sorts that multiple modules can write to, you can:

import saveState from './saveState';

saveState = { world: { } }; // Doesn't work
saveState.world = {};       // Does work

...not that I'd advocate such a pattern (shared state leads to all kinds of upredictability). Better to have a shared object with methods and have that object maintain an internal state.