1

I have Singleton implementation like this

var Singleton =  (function () {  
    var instance;

    function Singleton() {   

        if (!instance) {
            instance = this;
        }
        else {
            return instance;
        }
    }

    return Singleton;    
}());

And it's work if you create new object with new keyword, like

console.log(new Singleton() === new Singleton());

But if someone forgets to use new keyword, it doesn't work

console.log(Singleton() === Singleton());

The question is how to force function to be called as constructor-function, even without new keyword, to make these work:

console.log(Singleton() === Singleton());
console.log(new Singleton() === new Singleton());
console.log(new Singleton() === Singleton());
Max Brodin
  • 3,903
  • 1
  • 14
  • 23
  • 3
    `if (!Singleton.isPrototypeOf(this)){return new Singleton()}` – elclanrs Oct 28 '14 at 18:45
  • @elclanrs How is the question you marked as duplicate, an actual duplicate? That question asks *why* to force `new`, while this question is asking *how*. Your comment answers the question, but I don't see how the duplicate question does – Ian Oct 28 '14 at 18:47
  • 1
    Well, the question has the answer within it though, but I guess this a better dup http://stackoverflow.com/questions/1889014/can-i-construct-a-javascript-object-without-using-the-new-keyword – elclanrs Oct 28 '14 at 18:48
  • 1
    @elclanrs Is there a difference between your version and `this instanceof Singleton`? – Max Brodin Oct 28 '14 at 18:50
  • @elclanrs Well, I wouldn't consider that a duplicate then. I literally just found the same page (I had been searching), so I would re-close as a duplicate with that one (I reopened so you can close again) – Ian Oct 28 '14 at 18:50
  • @MaxBrodin, actually, just tried, and it won't work in this case, my bad. – elclanrs Oct 28 '14 at 18:54
  • 1
    @MaxBrodin, there is a difference, you should probably use `instanceof`, `isPrototypeOf` is convenient when doing inheritance with plain objects, and `Object.create`, but the way to do it would be `if (!Singleton.prototype.isPrototypeOf(this))` – elclanrs Oct 28 '14 at 19:00

0 Answers0