1

What is the proper way to create singleton in JS since ES2015? I know of many ways such as:

(() => {
  let instance;
  class Singleton{
    constructor(){
     instance = instance || this;
    }
  }
window.Singleton = Singleton; // or sth to export this class
})();
var a = new Singleton();
var b = new Singleton(); // a is the same as b

But it doesn't seem like a good way to use "new" operator with a Singleton class. So my question is whether there is a "proper" way to create a Singleton in ES6

Berrigan
  • 438
  • 4
  • 23
  • 1
    It's been asked before too. Check [here](http://stackoverflow.com/questions/1479319/simplest-cleanest-way-to-implement-singleton-in-javascript) – jakeehoffmann Apr 02 '17 at 14:40
  • It was before ES6, and this is what this question is about – Berrigan Apr 02 '17 at 14:50
  • Nothing changed in ES6. It is still JS. If you were after ES6 classes in particular, it's not clear why you accepted the answer that doesn't involve them. – Estus Flask Apr 02 '17 at 15:07
  • Don't use `class`es for singletons! Go with a simple object literal. – Bergi Apr 02 '17 at 16:08
  • `const singleton = {}; var a = singleton, b = singleton;` (you might want to show some real code if you want a real answer that actually does something) – Bergi Apr 02 '17 at 16:08
  • _"I know of many ways such as"_ This code doesn't create a singleton. – a better oliver Apr 03 '17 at 14:12

2 Answers2

1

This one seems to work for me:

let instance;

export default class AudioContext {

    static getInstance() {
        if (!instance) {
            instance = { 
                context:new window.AudioContext() || new window.webkitAudioContext(),
                contextCreatedAt: new Date()
            }
        }     
        return instance;
    }   
}

I have created 2 instances of AudioContext at different times. I then checked the time in contextCreatedAt (returns the same) and context === context on the 2 - however please elaborate if I am wrong here.

Dave Bleeker
  • 129
  • 1
  • 5
0
var a = (function () {

  // can put private vars/methods here.
  var a = 3;
  var b = 5;
  var sum = () => a+b;    

  return {// your singleton object
           getSum: sum 
           // ... 
         };

}());
jakeehoffmann
  • 1,364
  • 14
  • 22