DEV Community

yeonseong
yeonseong

Posted on

singleton in javascript

singleton in javascript

class Singleton
{
    constructor()
    {
        if (!Singleton.instance)
        {
            Singleton.instance = this;
        }
        return Singleton.instance;
    }

    getInstance()
    {
        return this.instance;
    }
}
Enter fullscreen mode Exit fullscreen mode

test

const testA = new Singleton();
const testB = new Singleton();

console.log(testA === testB); // true
Enter fullscreen mode Exit fullscreen mode

singleton example (db connection)

const URL = "db_url";
const createConnection = url => ({"url" : url});
class DB
{
    constructor(url)
    {
        if (!DB.instance)
        {
            DB.instance = createConnection(url);
        }
        return DB.instance;
    }

    connect()
    {
        return this.instance;
    }
}
Enter fullscreen mode Exit fullscreen mode

profits of singleton

save cost of creating instance.

disadvantage of singleton

high coupling
(can be resolved DI(dependency injection))

Top comments (0)