Instead of my usual blog post, I'd like to pose a question.
How often do you JavaScript developers use singleton patterns?
If I wanted to implement a singleton pattern in ES6, is this how I'd do it?
If not, why not?
// notifications.js
class Notifications {
constructor() {
this.messages = [];
}
add(message) {
this.messages.push(message);
}
}
export const notifications = new Notifications();
// ☝️ asking about this
// main.js
// 👇 less important
import { notifications } from './notifications';
class Main {
constructor() {
notifcations.add('some message')
}
}
new Main();
Top comments (3)
Not sure you can have a private constructor in js...
That said, you don't really need singletons in JS... Using functions inside es6 modules do the exact same job (you can even store a state inside modules).
You can have a private constructor in TypeScript. But all is lost when transpiled down to JavaScript.
l would separate the class definition and the shared instances, putting them in different modules.
Then you can have as many "singletons" as you need.