OutputNot attempted
A frozen singleton
class ConfigSingleton { constructor() { if (ConfigSingleton.instance) return ConfigSingleton.instance; this.started = false; ConfigSingleton.instance = this; Object.freeze(this); }}const a = new ConfigSingleton();const b = new ConfigSingleton();console.log(a === b);try { a.name = 'Robert';} catch (e) { console.log(e.name);}console.log(Object.keys(a), ConfigSingleton.instance === a);Spaces and quote style don’t matter · write a thrown error as TypeError
Ctrl Enter
Show answer & explanation
The expected output comes from actually running the snippet; opening this shows it next to the explanation.
A constructor that RETURNS an object makes new give back that object, so the second new returns the cached instance. Because it is frozen, adding a property throws TypeError in strict mode (it would be silently ignored in sloppy mode).