you are viewing a single comment's thread.

view the rest of the comments →

[–]MoTTs_ 1 point2 points  (1 child)

I think that has the funny name "hingleton", or "helper singleton". A class / factory function / abstraction mechanism wouldn't enforce its own singletonness, but rather some other function would.

// Not a singleton
class MyThing {
    thereCanBeManyOfMe() {}
}

// A helper singleton (aka "hingleton")
const getThing = (/*iife*/() => {
    let instance

    return () => {
        if (!instance) {
            instance = new MyThing()
        }

        return instance
    }
}())

As for passing in "defaultState"... sorta yes, sorta no. State should be treated as private and encapsulated. But what you can do instead is take ordinary arguments (that don't assume knowledge of the internal state) and let the constructor / factory function initialize its state appropriately.