Singleton without a closure
Warning: anti-pattern ahead.
Mwahaha, I feel like a ninja. I mean a ninja by Doug Crockford's definition which means someone who finds a mistake in the language's design, decides it's cool and abuses it.
So there you go. Regular expression objects are created only once if you're using a literal. Such an object can be used to store the single instance of a Singleton() constructor.
Implementation
function Single() { "strict me not!"; var re = / /; if (re.instance) { return re.instance; } re.instance = this; this.name = "Foo"; } Single.prototype.getName = function () { return this.name; };
Test
var s1 = new Single(), s2 = new Single(); console.log(s1 === s2); // true console.log(s1.getName()); // "Foo" s1.name = "dude"; console.log(s2.getName()); // "dude"
Pros
- The prototype chain works fine
- No closures
- No public properties or globals to store the single instance
Cons
- It's a hack
- ES5 defines that reg exp literals should no longer work like this
Verdict
Don't use. Please 🙂
Tags: singleton