« »
2/12/2015

So it isn't possible to create a clean Singleton in JavaScript due to constructor restriction? Really?

As I am currently preparing a lecture on Design Patterns, I started to read the famous Design Patterns: Elements of Reusable Object-Oriented Software a.k.a the Gang of Four book as well as Les design patterns en Java and Mastering JavaScript Design Patterns.

Whether or not Design Patterns in oriented programming language are a language smell is another story (even if I could not personally agree more). I wanted to write about the following affirmations in Mastering JavaScript Design Patterns:

My first reaction  reading this was:
The second check inside the Wall constructor is hideous and we can definitely hide the constructor thanks to a closure, leveraging JavaScript functional nature. I thus gave this affirmation as an exercise for my students and here is a possible solution:


But we can go even further, why bother duplicating singleton logic when you can make a Singleton factory:

Note that the Singleton factory invocation must be alongside the internal implementation otherwise the JavaScript constructor could be instantiated multiple times.

Bonus: a lot of Singleton implementations available on Internet forgot to hide the constructor, even Addy Osmani books on JavaScript Design Patterns forgot this:

PS: The __proto__ trick for hiding the constructor is now widely supported (IE11+).

[Update] Supporting static methods and leveraging Object.create features instead of redefining __proto__.constructor:

« »
 
 
Made with on a hot august night from an airplane the 19th of March 2017.