DEV Community

Discussion on: Singleton in JavaScript

Collapse
 
smalluban profile image
Dominik Lubański • Edited

Regardless singleton is right or not, there is a way to create a class, that can be extended and be a singleton for own type only.

Instead of using hard reference class constructor you should use constructor property of the instance.

class SingletonClass {
    constructor(name = "") {
        if (!!this.constructor.instance) {
            return this.constructor.instance;
        }

        this.constructor.instance = this;

        return this;
    }
}

this.constructor is a reference to the direct constructor function.

Collapse
 
tomekbuszewski profile image
Tomek Buszewski • Edited

I'm not sure I understood you correctly, you mean using this I can create another class that will extend the SingletonClass? Then SingletonClass isn't a singleton, because, by definition, it cannot be extended.

Plus, I have tried something like this and failed, can you provide the code?

Collapse
 
smalluban profile image
Dominik Lubański

I forgot about constructors prototype chain :P

Here you have working example:

Thread Thread
 
tomekbuszewski profile image
Tomek Buszewski

This is not a singleton class now :) But nevertheless, excellent example.