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 require
d.
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?