DEV Community

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

Posted on • Edited on

2 1

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

Top comments (3)

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.

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.

nextjs tutorial video

Youtube Tutorial Series 📺

So you built a Next.js app, but you need a clear view of the entire operation flow to be able to identify performance bottlenecks before you launch. But how do you get started? Get the essentials on tracing for Next.js from @nikolovlazar in this video series 👀

Watch the Youtube series

👋 Kindness is contagious

Explore a trove of insights in this engaging article, celebrated within our welcoming DEV Community. Developers from every background are invited to join and enhance our shared wisdom.

A genuine "thank you" can truly uplift someone’s day. Feel free to express your gratitude in the comments below!

On DEV, our collective exchange of knowledge lightens the road ahead and strengthens our community bonds. Found something valuable here? A small thank you to the author can make a big difference.

Okay