title: Singleton in JavaScript with module.export and require?
body: <p>I am trying to implement Singleton in JavaScript where I use Node.js module.export and <code>require()</code>.</p>
  
  <p>My issue is that module.export so far for me returns new object from a class.</p>
  
  <p>If I make it so that all classes are only available requiring them from Singleton class and not <code>require()</code> - then would I guarantee that I will have one instance only?</p>
  
  <p>Because if all Other classes import from Singleton - how should I import Singleton?</p>
  
  <p>In php no matter how many instances of Singleton you have - each share static properties. So if you make the instance static then all Singleton's no matter in which files they are invoked have the same memory and perform the same action.</p>
  
  <p>However I have no idea what is the case with JavaScript</p>
  
  <p>I also have another approach - If I make <code>let instance</code> variable at the start of the file and check if its empty at the end and if it isn't I make another instance <code>instance = new MyClass()</code> and then <code>module.export = instance</code>. Would this give me the same result?</p>
  
  <p>For example what I currently do</p>
  
  <pre><code>class MyClass {
      //some logic here
  }
  module.export = new MyClass()
  </code></pre>
  
  <p>What I think of doing but no idea if it is good or it will work</p>
  
  <pre><code>if(!instance){ 
      let instance = 1;
  }
  class MyClass {
      //some logic here
  }
  if(instance === 1){
     instance = new MyClass()
  }
  module.export = instance
  </code></pre>
  
  <p>Also to make matter more complicated I have seen several versions of implementations</p>
  
  <p>Here -> <a href="https://www.sitepoint.com/javascript-design-patterns-singleton/" rel="noreferrer">https://www.sitepoint.com/javascript-design-patterns-singleton/</a></p>
  
  <p>There are 3 examples - </p>
  
  <p>1.Old JS ECMA 2015 way with functions</p>
  
  <p>2.ECMA 2016 with object literal instead of class</p>
  
  <p>3.With classes but again Object.freeze and const</p>
  
  <p>Now..these versions make use of Object.freeze which I am not familiar with and const variables...which I am also not perfectly sure how they work.</p>
  
  <p>To recap (TL;DR) - What I want to do is a way so that if I require a class in 10 files with <code>require("MyClass")</code> I won't get 10 instances but only 1.</p>
  
  <p>Does my way work properly and are the examples in the link with <code>Object.freeze()</code> and the use of <code>const</code> good working examples?Do I need an anctual Singleton class to do the job? Because solutions so far don't include one. And If I need - how do I pass that Singleton around so it has only one instance?</p>