0

Thanks to this awesome answer I was able to put something like a singleton pattern into my JavaScript application (single page). Unfortunately I still have problems with understanding how this actually works. This might be related to me not really understanding how a require() call actually works in detail.

To quote the linked answer:

The first require to the module will load and export it. Some other module requiring your singleton will just reuse the already exported one.

(still quoting)

define(function (require) {
    var singleton = function () {
        return {
            ...
        };
    };
    return singleton();
});

So the process is as follows, just to make sure I understood it. If there is anything wrong, please correct the process description.

In module A, I pull in the singleton module.

Inside that module, a function that returns an object is defined. The module's return/export value is the result of that function.

Now in module B, I also require the singleton module and get back the same object that was created when the singleton was first required.

Where does the singleton data live between the first and the second require?

I just don't get how this object sharing works, I always imagined the require as some kind of "virtual pasting", but this seems to be pretty wrong. What is actually happening?

Community
  • 1
  • 1
Sven
  • 12,997
  • 27
  • 90
  • 148

1 Answers1

0

Your code resembles a static instance more than a singleton. If your code lived in a file called 'test' and I did this:

var myFunc = require('./test');

when the above line runs, myFunc will be the function defined in your code.

However, a true singleton is not initiated until requested like so:

define(function(require){ 
  return (function () {

      // Instance stores a reference to the Singleton
      var instance;

      function init() {

        // Singleton

        // Private methods and variables
        function privateMethod(){
            console.log( "I am private" );
        }

        var privateVariable = "Im also private";

        var privateRandomNumber = Math.random();

        return {

          // Public methods and variables
          publicMethod: function () {
            console.log( "The public can see me!" );
          },

          publicProperty: "I am also public",

          getRandomNumber: function() {
            return privateRandomNumber;
          }

        };

      };

      return {

        // Get the Singleton instance if one exists
        // or create one if it doesn't
        getInstance: function () {

          if ( !instance ) {
            instance = init();
          }

          return instance;
        }

      };

    })();
}

Check out: https://addyosmani.com/resources/essentialjsdesignpatterns/book/#singletonpatternjavascript

N R
  • 9
  • 2