0

I'm following this article. I understood what singleton pattern is but I'm not be able to understand the code.

let Singleton = (function(){
    let instance = null;

    function createInstance() {
        let obj = new Object("I am the new instance");
        return obj;
    }

    return {
        getInstance:function() {
            console.log(instance);
            if(instance === null) {
                instance = createInstance();
            }
            return instance;
        }
    }
})();

function test() {
    let instance1 = Singleton.getInstance();
    let instance2 = Singleton.getInstance();
    console.log(Object.is(instance1,instance2));
}
test();

why instance1 and instance2 are same, we are always initializing the instance to null whenever we call Singleton.

1 Answer 1

1

we are always initializing the instance to null whenever we call Singleton.

You do not. Singleton is the object in the return statement, which does not include the statement let instance = null. This statement is only executed once; this variable is captured under closure in getInstance method of the returned object (Singleton.getInstance). The code is equivalent to

let instance = null;

function createInstance() {
    let obj = new Object("I am the new instance");
    return obj;
}

let Singleton = {
    getInstance: function() {
        console.log(instance);
        if (instance === null) {
            instance = createInstance();
        }
        return instance;
    }
}

except that instance and createInstance are hidden inside the IIFE's scope.

You can verify how many times (and when) let instance = null executes by inserting more logging statements.

Sign up to request clarification or add additional context in comments.

1 Comment

Got it, I was interpreting Singleton as a function but is actually an object with getInstance property. Thank you Amadan.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.