Microsoft Ajax JavaScript library is one the powerful libraries on the market, even is not so popular any more. More and more developers are going into jQuery direction, but I still continue to use on daily basis, as I am working in SharePoint environment.
For today, I have created a very simple example of singleton pattern based on this library. In essence, is not different at all than pure JavaScript, but the purpose of this is to show to other Microsoft Ajax enthusiastic developers how can integrate this pattern into their code.

/// <Reference Name="MicrosoftAjax.js" />


NS.Singleton = function () {
    /// <summary>Constructor for our singleton class</summary>
    if (NS.Singleton._instance !== null) {
        throw "An instance of NS.Singleton already exists"
    NS.Singleton._instance = this;

// Stores the instance of Singleton class
NS.Singleton._instance = null;

NS.Singleton.get_instance = function () {
    /// <summary>Return single instance of NS.Singleton</summary>
    if (NS.Singleton._instance === null) {
        return new NS.Singleton();
    else {

NS.Singleton.prototype = {
    firstMethod: function () {
        alert('This is first method');
    secondMethod: function () {
        alert('This is second method');


So, we have a class called “Singleton”, included into “NS” namespace, and we want to have only one instance of this class in the application. For this I have created a static property “_instance” of this class where we store the instance. I used “_” in the name as, by convention, private properties or method should start with this sign in the absence of access modifiers in JavaScript. Visual Studio is quite good on the intellisense and won’t trigger the auto complete for private properties.

Besides this, we need also a static method called “get_instance” to create an instance or return existing one.

var instance_one = NS.Singleton.get_instance();
var instance_two = NS.Singleton.get_instance();

In this example, instance_one and instance_two variable contains the same reference to the instance of NS.Singleton.

It might appear for you a little bit different than classical examples, but in essence is doing the same thing. In any case, if you decide to use Microsoft Ajax library, this is a working example.