Singleton Pattern in JavaScript

If you know the Singleton Pattern from Java, then this is what you need, to implement a Singleton in JavaScript:

singleton.js

var Singleton = (function(){
  var instance = null;
 
  function PrivateConstructor(){
    var number = Math.round(Math.random() * 100);
    var text = 'Change me.';
 
    this.setNumber = function(numberValue){
      number = numberValue;
    }
 
    this.getNumber = function(){
      return number;
    }
 
    this.setText = function(textValue){
      text = textValue;
    }
 
    this.getText = function(){
      return text;
    }
 
    this.saySomething = function(){
      alert(text);
    }
  }
 
  return new function(){
    this.getInstance = function(){
      if (instance == null){
        instance = new PrivateConstructor();
        instance.constructor = null;
      }
      return instance;
    }
  }
})();

How to use it:

<script src="./js/singleton.js"></script>
<script>
  var firstInstance = Singleton.getInstance(); 
  var secondInstance = Singleton.getInstance(); 
 
  if(firstInstance === secondInstance){
    document.write('We have two instances.<br/>');
  }        
 
  document.write(firstInstance.getNumber()); 
  document.write('<br/>');      
  document.write(secondInstance.getNumber());
  firstInstance.setText('Hello World.');
  secondInstance.saySomething(); // displays 'Hello World.'
</script>

Without constructor:/h2>

var Singleton = (function() {
  // Private
  var text = "Hello World!";
 
 
  // Public
  return {
    setText: function(value) {
      text = value;
    },
    getText: function() {
      return text;
    }
  };
})();
 
alert(Singleton.getText());

Schreibe einen Kommentar

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert

Diese Website verwendet Akismet, um Spam zu reduzieren. Erfahre mehr darüber, wie deine Kommentardaten verarbeitet werden.