0

I am trying to make a Singleton class constructor in Javascript. But I am getting an error. Taking Java analogy, what I did was :

var ob1 = (function getSingleton() {
    var privateData;
    if(this.privateData !== null) {
        this.privateData = new getSingleton();
        return this.privateData;
    }
})();

But I am getting the following:

Uncaught RangeError: Maximum call stack size exceeded.

What am I conceptually doing wrong? Or, how can it be made perfect?

StrugglingCoder
  • 4,781
  • 16
  • 69
  • 103
  • 4
    `this.privateData = new getSingleton();` is recursively creating a new instance, hence the error. – briosheje Jan 24 '18 at 13:42
  • 2
    Possible duplicate of [Simplest/Cleanest way to implement singleton in JavaScript?](https://stackoverflow.com/questions/1479319/simplest-cleanest-way-to-implement-singleton-in-javascript) – Serge K. Jan 24 '18 at 13:42
  • @briosheje But I am checking right if it's not null? So once the function executes, it creates the instance and assigns it. Going forward, it should not be creating instances. What am I missing here ? – StrugglingCoder Jan 24 '18 at 13:46
  • 2
    @StrugglingCoder: No, because you are creating a **new** object, which will be, by default, empty. That's not the way you should do it, check Serge's link to properly implement a singleton class. You should **never ever** have a recursive constructor in this situation. About your question, there are two additional errors: `var privateData` is different from `this.privateData`. Moreover, `this.privateData` is `undefined`, not null. Hence the maximum call stack size exceeded (because it's `undefined`, which is different from `null`) – briosheje Jan 24 '18 at 13:48
  • Why do you need a singleton? Why not just make ob1 an instance of the object and then be done with it? Aren't they just the "...political correct name for global variables on OO"? https://stackoverflow.com/questions/2551112/purpose-of-singletons-in-programming – TheCrzyMan Jan 24 '18 at 13:53

0 Answers0