September 2018
Intermediate to advanced
302 pages
7h 17m
English
To be honest, beyond just the previous implementation, we can see many other variations in order to achieve the same thing. Let's discuss them.
In the following code, the singleton has already been exported as an instance:
class Singleton { static instance; constructor() { if (Singleton.instance) { return Singleton.instance; } this.instance = this; }}export default new Singleton();
This looks like a good improvement unless your Singleton requires arguments. If so, the Singleton is exported in such a way that it is also harder to test and may only accept hard-coded dependencies.
Sometimes, your Singleton may be very small and only an object will be enough:
export default { apiRoot: API_URL, fetchData() ...Read now
Unlock full access