The JavaScript Singleton Pattern – Part III   Leave a comment

Jean Lafitte Swamp. Photo By dlr2008

The Singleton Saga – Part I
The Singleton Saga – Part II
The Singleton Sage – Part III

Welcome To Side Three.

The Singleton Pattern has been explored by Douglas Crockford among others. I first stumbled on the  Concept in a chapter of Harmes and Diaz’s book, Pro JavaScript Design Patterns. The Singleton Pattern is an anti-inheritance pattern. It is designed for situations where we which to create a single Component. For example, a Query String Reader Component is a good candidate to use the Singleton Pattern, since

  • The component makes little sense to have multiple Query String Readers on a single page;
  • the component is a good candidate for inclusion in a JavaScript support library;
  • The component can be created with no external side-effects or dependencies;

An bare bones abstract definition of a Query String Reader component might be given as:

  • The component is initialized with a reference to the query string location (i.e.
  • A public method could be defined as: (using C# syntax)
    • Public string GetValue(string Key);
      • This method returns the value associated with the Query String Key, or
        • Throws an exception if the Key is not found in the Query String.

In C# we might express this definition as

Public class QueryStringReader{
String  _OrigianlQueryString;//private string
Public QueryStringReader(string originalQueryString){..}// initialization step for this class
Public string GetValue(string key){…}

The Interface Definition for this object/class (in C#) might look like

Public interface iQueryStringReader{

String GetValue(string key);


What we would like to achieve in JavaScript is a component which roughly parallels these abstract

definitions. Note: I am using C# syntax here, because that my ‘native’ language. The abstract

definition expressed in Java is very similar. We will not build the QueryString Reader in this post.

By friend and coding associate, cle, is building one now using the singleton pattern. I promise to share

It with you when he is done. Interestingly, type “query string reader JavaScript” in your favorite

Search engine and you get about 500,000 hits! Instead, we will build a “talking dog” Singleton

Component. (With a talking dog, we don’t care so much about what the dog says, but that s/he talks at all). So let’s return to JavaScript now to do so.

Ok, so what do we want this talking dog to do? First let’s define the abstract features shared by all

Singleton Components:

  • Modular Design
    • no side effects or external dependencies
  • Namespace Minimization
    • The class requires, at most, one (page) global variable.
  • Private fields
    • internal fields (variables) which retain values between calling to the object
  • Private Methods
    • internal methods which can reference other private methods and fields
  • Public Methods
    • Multiple public methods, but
      • A limited set of non-contingent public methods
    • Public method which can reference private methods and fields
      • without using a context prefix (this or that)
      • See Part II of this series if this is unclear.
  • Does not use the JavaScript “new” verb
  • Supports an Instance Initialization method
    • ctor in C# terms
  • Clear separation of interface and implementation

[Note: I will use the terms function and method interchangeably in this post. One should remember

that function (methods) are actually full JavasScript Objects, with all that that implies.]

Now lets define the Talking Dog Component

  • Public Interface:
    • public iTalkingDog{
      void Speak();
      void Set(string WordToSpeak);
  • Initialization:
    • Provide the first work to speak on initialization.
  • Behavior:
    • Set(string)
      • Sets the word to speak.
    • Speak()
      • Sends the word to speak to the alert box method.
  • Model Usage:
    Var talkingDog={magic code appears here}('bark');
    talkingDog.Speak();  //alertbox show: 'bark';

Show Us Some Code

var talkingDog=(
var _word=startupWord;
function _speak(arg){
function _Set(arg){
Speak : function (){ return _speak(_word);},
Set : function(arg){ return _Set(arg);}

let’s break this down a bit. Start with the ZEN sequence

I. ZEN! Do Nothing but do it right now.


II. More ZEN! Do Nothing and safe the results as an empty JavaScript Object

var doNothing=()();//but do it right now

Add an anonymous private method.

var privateThing=(function(){})();

Expanded with notes:

var privateThing=(
function(arg){//defines anonymous method here

III. Store initialization argument object.

var doNothing=(
function(arg){//the anonymous method receives 'bark' as an argument
var _Word=arg;//and saves it for future reference

Still nothing visible or functional.

IV. Define a private named function within the outer anonymous function.

var doNothing=(
function(arg){//the anonymous private method, receives 'bark' as an argument
var _Word=arg;//and saves it for future reference
function _speak(arg){ //inner private function
alert(arg);//Display the contents of arg in an alert box

Still nothing visible or functional

IV. Define The Public Methods (aka The Public Interface)

var talkingDog=(
var _word=arg; 
 function _speak(arg){ 
return {//define  public method(s)
Speak : function (){ 
 return _speak(_word); 
}//end of public method: Speak
}//end of public interface
}//end of outer anonymous function

The dog can speak, at last.

Jazz Fest Trio. Photo By dlr2008

Some Additional Technical Notes:

Composed this way, public methods can safely reference private fields and methods, directly and unambiguously. (say closure three times and click your heels) Public methods cannot safely reference other public methods. The syntax is triple tricky. The public interface (Redcode in Listing V) is JSON syntax( Separate JSON items with commas).

The private implementation (Green Code in Listing VI) are defined using normal JavaScript syntax (Separate statements with semi-colons). Green Code mixes executable code (var _word=arg;) with declarative code (function _speak(arg){…}).   Private methods may refer to other private methods and fields unambiguously.  Private methods can not reference public methods.

The (RED) Public Interface Section is basicallydeclarative and is evaluated when called (using the context of the anonymous method, not the context of the caller).

Magic Beans, for sure.

You’ve Been Warned.


The Singleton Saga – Part I
The Singleton Saga – Part II
The Singleton Sage – Part III

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: