Quantcast
Channel: Singleton Pattern in Javascript - Stack Overflow
Viewing all articles
Browse latest Browse all 3

Answer by nullable for Singleton Pattern in Javascript

$
0
0

Not much going on here. The main focus should be on the constructor, it is returning an instantiated Universe for you. So anyone that calls it will have a reference to the same instance. Notice how the constructor is pointing to the Universe function.

I wouldn't use this pattern, as the new keyword implies a new instance is being created, and it seems a little too esoteric for my taste. In JS you can perfectly just have an object literal, often used with a namespace pattern:

(function(ns, window, undefined) {
    ns.singleton = {
        bang: 'Big'
    };

    window.ns = ns;
})(ns || {}, window);

console.log(window.ns.singleton.bang === 'Big');

Granted, this isn't a true singleton, but it does not need to be instantiated, and anyone who uses it will have the same values.

For more singleton implementations, see Javascript: best Singleton pattern


Viewing all articles
Browse latest Browse all 3

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>