mercredi 18 août 2021

Design pattern - Singleton pattern in JavaScript

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.

Aucun commentaire:

Enregistrer un commentaire