Singleton Pattern in JavaScript

Singleton Pattern in JavaScript

A simple singleton pattern for JavaScript classes.

class Instances = {};

class MyClass {
    static get() {
    	if (Instances[] === undefined) {
        	Instances[] = new this();
        return Instances[];

Call ```MyClass.get()``` to get a single instance of MyClass. All subsequent calls to .get() will return the same instance.

This works because "this" still has a valid context when used within static functions in JavaScript. "this" actually refers to the class itself, so you can use "this" to spawn new instances, query the class name, etc.

This is a clean implementation for child classes too. If you extend MyClass with your own class, your new child class will get it's own instance.

class ChildClass extends MyClass {

const ClassInst = MyClass.get();
const ChildInst = ChildClass.get();

console.log(ClassInst == ChildInst); // false

You can use this to have a master "Singleton" class that handles all your singletons, or just include the small code snippet in a class you need to be using singleton logic for.