DEV Community

Cover image for Singleton Pattern in JavaScript?
Aryan J
Aryan J

Posted on • Updated on

Singleton Pattern in JavaScript?

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();
Enter fullscreen mode Exit fullscreen mode

Latest comments (3)

Collapse
 
pentacular profile image
pentacular

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.

Collapse
 
devdufutur profile image
Rudy Nappée

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).

Collapse
 
patarapolw profile image
Pacharapol Withayasakpunt

You can have a private constructor in TypeScript. But all is lost when transpiled down to JavaScript.