Never been to TextSnippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world (or not, you can keep them private!)

« Newer Snippets
Older Snippets »
2 total  XML / RSS feed 

Factory patterns in Javascript


Suppose that you don't know the exact class that should be created until runtime. In the case of JavaScript, this may be due to browser differences. The best example of this today is in creating XMLHttp objects. A lot of times, you'll see code that looks like this:
if (typeof XMLHttpRequest != "undefined") {
    return new XMLHttpRequest();
} else if (typeof window.ActiveXObject != "undefined") {
    return new ActiveXObject("MSXML2.XMLHttp");
}

Clearly, you don't want to repeat this code every time you need to create a new XMLHttp object.

The factory pattern involves having a function (or an object with a method) that returns the appropriate object. Developers need not know which object is being returned since the interface will be the same no matter what. You need only call the function and know that the correct object will be returned. For example:
function XMLHttpFactory() {
}

XMLHttpFactory.createXMLHttp = function () {
    if (typeof XMLHttpRequest != "undefined") {
        return new XMLHttpRequest();
    } else if (typeof window.ActiveXObject != "undefined") {
        return new ActiveXObject("MSXML2.XMLHttp");
    }
} 

With this defined, developers can now use a single method call to create the object that will work for their environment:
var oXMLHttp = XMLHttpFactory.createXMLHttp();

Singelton in Javascript


function MyClass() {
   if (MyClass.caller != MyClass.getInstance) {
       throw new Error("There is no public constructor for MyClass.");
   }

   this.myproperty = "hello world";
}

MyClass.__instance__ = null;  //define the static property

MyClass.getInstance = function () {
    if (this.__instance__ == null) {
        this.__instance__ = new MyClass();
    }

    return this.__instance__;
}


Checking for the MyClass.caller != MyClass.getInstance in MyClass constructor will suppress the ability of the developer to do this:
var oMyObject = new MyClass();
« Newer Snippets
Older Snippets »
2 total  XML / RSS feed