Page 1 of 1

Singleton in JavaScript

Posted: Thu Aug 10, 2006 4:04 am
by Chris Corbyn
Not so much a question, more of a useful resource pointer.

After reading articles by people who don't know what they're talking about, like this:

http://dhtmldev.com/content/view/27/26/ (Don't take this on-board - it's wrong!)

WTF do they mean?? In their own terms JS is not an object oriented language?? OK then whatever... I always wondered what all the dot syntax was about... they obviously just like full-stops :?


I finaly found a good implementation here:

http://www.webreference.com/programming ... mn5/2.html

It can be done with static properties just like PHP :)

I needed this for some Request/Response objects in a pretty dynamic interactive ajax application and for Input/Output objects. Works a peach.

Posted: Thu Aug 10, 2006 11:56 am
by Weirdan
It can be done with static properties just like PHP
What is wrong with this approach it that instance variable remains public

Posted: Thu Aug 10, 2006 12:22 pm
by Weirdan
what I would suggest is to use one-off anonymous function to form a closure to hold private static variable:

Code: Select all

var MyClass = (function() {
    /*private static (class) member*/
    var __instance__ = null;
    var counter = 0;

    /*class constructor.*/
    function constructorFn() {
        var self = this;
        if (constructorFn.caller != constructorFn.getInstance) {
            throw new Error("There is no public constructor for MyClass.");
        }
        self.myproperty = "hello world";
        counter++; // increment instance counter (for debugging purposes)
    };

    /*privileged static (class) method
    (a property of the constructor)*/
    constructorFn.getInstance = function() {
        if(this.__instance__ == null) {
            this.__instance__ = new constructorFn();
        }

        return __instance__;
    };
    constructorFn.getInstanceCount = function() {
        return counter;   
    }
    /*return the constructor.*/
    return constructorFn;
})(); //simultaneously define and call (one-off)!
// attempt to create new object:
try {
    var q = new MyClass();
} catch(e) {
    alert(e.toString()); // should fail
}
var a = MyClass.getInstance();
var b = MyClass.getInstance();
alert('Total instances of MyClass: ' + MyClass.getInstanceCount());
This is the direct application of technique described by Richard Cornford at http://www.litotes.demon.co.uk/js_info/ ... tatic.html (very nice paper, btw)

Posted: Thu Aug 10, 2006 1:01 pm
by Chris Corbyn
Thanks for the info Weirdan... I'll have a read over that paper later :)