Some objects should exist once per page: the app's settings, a connection to a socket, a cache that every module reads. If two modules each build their own, one changes the theme and the other never sees it. A singleton is a class that only ever has one instance, and hands that same instance to everyone who asks.
Write the class Settings in settings.js. Settings.getInstance() returns the one instance, and so does new Settings(). The instance stores values by key.
classSettings {staticgetInstance() // the one instanceget(key) // the stored value, or undefinedset(key, value) // stores value; returns the instancehas(key) // true when key was set}
Settings.getInstance() returns a Settings object, and the same object on every call.
new Settings() returns that same instance too, every time.
set(key, value) stores the value and returns the instance; get(key) returns what was stored (the same object, not a copy); a second set replaces the value.
A value set through one reference is seen through every other reference.
new Settings() never clears or resets the values already stored.
get returns undefined and has returns false for a key never set; has is true for a key set to undefined.
Every string is an ordinary key: has("toString") and has("constructor") are false until they are set, and "__proto__" stores and returns a value like any other key.
The instance has no own properties.
Outside code cannot replace the instance: the class has no static property other than getInstance (besides the built-in length, name and prototype), and assigning Settings.instance changes nothing.
getInstance still works when called on its own: const { getInstance } = Settings; getInstance().