DEV Community

loading...

Discussion on: Singleton Pattern in Javascript

Collapse
chayimfriedman2 profile image
Chayim Friedman • Edited

I would do it this way:

const Singleton = (function() {
    let instance = null;
    return class Singleton {
        constructor() {
            if (instance !== null) { return instance; }
            instance = this;
            // Init properties...
        }
        // ...
    };
})();
Enter fullscreen mode Exit fullscreen mode

Allowing you to use new:

console.log(new Singleton() === new Singleton()); // true
Enter fullscreen mode Exit fullscreen mode

Of course it can be done without ES6 classes too:

const Singleton = (function() {
    let instance = null;
    return function Singleton() {
        if (!new.target) { throw new Error("`Singleton()` must be called with `new`"); }
        if (instance !== null) { return instance; }
        instance = this;
        // Init properties and set methods...
    };
})();
Enter fullscreen mode Exit fullscreen mode
Collapse
bibekkakati profile image
Bibek Author

Yeah, that can be a way of implementing it.

Forem Open with the Forem app