javascriptdesign-patternssingleton

Does javascript singleton require double parentheses?


function GetFinder(){
    let Pub = {}
    let Priv = SingletonFinder().getInstance()()
    // the rest of the code...
}

function SingletonFinder() {
    let Priv = {}
    let Pub = {}

    /** @type {Class_Finder} */
    Priv.instance = null;
    Priv.createInstance = function () {
        return Class_Finder
    }
    Pub.getInstance = function () {
        if(!Priv.instance) {
            Priv.instance = Priv.createInstance()
        }
        return Priv.instance
    };
    return Pub
}

function Class_Finder() {
    // properties
}

Solution

  • Years later, after reviewing this project, I can conclude that:

    The following code exemplifies why ()() is necessary to output 'true':

    const obj = {};
    const fn = ()=>{return true}
    obj.method = ()=>{return fn}
    
    console.log(obj.method) //output: function
    console.log(obj.method()) //output: function
    console.log(obj.method()()) //output: true
    

    Finally, it was all for fun! I've never been a pro coder and was just being a total beginner. Patterns fascinated me at the time as much as experimenting with coding and browsing the communities online.