DEV Community

Srinivas Kandukuri
Srinivas Kandukuri

Posted on

Write Singleton in JavaScript

Def : Ensure a class has only one instance and provide a global point of access to it.

Example

var shoppingCart = (function(){
    var items= [];
    function createinstance(){
        return {
            getItems : function(){
                return items;
            },
            addItems : function(item){
                items.push(item);
            }
        }
    }

    return {
        GetInstance : function(){
            return createinstance();
        }

    }
})();
Enter fullscreen mode Exit fullscreen mode

Adding items to Shopping Cart

shoppingCart.GetInstance().addItems("one");

shoppingCart.GetInstance().addItems("two");
Enter fullscreen mode Exit fullscreen mode

Get the items from Shopping Cart

console.log(shoppingCart.GetInstance().getItems());
Enter fullscreen mode Exit fullscreen mode

Top comments (0)