I’m pretty sure I don’t need to go over the benefits of having a singleton, especially in javascript when you often want to avoid using a global variable whenever possible.

I want to apoligize for the poor formatting of the script, I don’t have the luxury of some of the awesome wordpress plugins out there.

First, lets create a generic object with some base init logic.

function BatmanObj() {
this.mInit = fnInit;
this.mInit();
function fnInit() {}
}

So here we have our Batman object, and we want to always know that we can get the BatMobileObj, and who knows, batman may need access to his BatMobile too.

To do this, we Reference the Objects name, then our property or methods signature.

// Makes Current a reference to an instance of
//the BatmanObj  
BatmanObj.Current = new BatmanObj();  
// Makes mTurnOnSpotlight a static Method.  
BatmanObj.mTurnOnSpotlight = function() {  
return BatmanObj.Current;  
}

One of the conditions we need to start defining Static Methods and Properties is an instance of an object, so we can’t do it in the container of the object, or outside the definition but its perfectly fine to do in our handy fnInit function.

function BatMobileObj() { }  

function BatmanObj() {  
// Bad, Error, Crash and Burn
BatmanObj.xBatMobile = new BatMobileObj(); 
this.mInit = fnInit;  
this.mInit();  

function fnInit() {  
// Yay, Success!! 
if(!BatmanObj.xBatMobile)  
BatmanObj.xBatMobile = new BatMobileObj();  

if(!BatmanObj.Current)  
BatmanObj.Current = this;
}
}

The Singleton is only valid once the object is instantiated, but, is good beyond that.

3 comments

3 Responses to “Javascript Singleton using static properties”

  1. zproxy Says:

    Why not simply do like this:

    function MyObject { };

    MyObject.MyStaticField = new MyObject();

  2. justise Says:

    I could do that, but then how would I point out that you need your object defined first?

    Static objects while interesting, don’t have to much to them, thus I have been caught trying to Dilbertize an article.

  3. Javascript Singleton Part II « Means Nothing Says:

    […] Singleton Part II So I wrote that Singleton post a few weeks ago, and what it really turned into is how to initialize Static Properties. Though […]

Leave a Reply