mogedw
Last Updated: February 25, 2016
·
517
· timsommer

Javascript Static Singleton

In conventional software engineering, the singleton pattern can be implemented by creating a class with a method that creates a new instance of the class if one doesn't exist. In the event of an instance already existing, it simply returns a reference to that object.

jsfiddle link: http://jsfiddle.net/timsommer/thxn4/

var SingletonTester = (function () {
    //This is the actual singleton instance
    function Singleton() {
        this.name = "Singleton";
        this.pointX = 16;
    }

    // this is our instance holder
    var instance;

    // this is an emulation of static variables and methods
    var _static = {
        name: 'SingletonTester',
        // This is a method for getting an instance
        // It returns the same instance of the singleton object
        getInstance: function () {
            if (instance === undefined) {
                instance = new Singleton();
            }
            return instance;
        }
    };
    return _static;
})();

//getInstance method is the only method we can call on the returned _static object
var singletonTest = SingletonTester.getInstance();

console.log(singletonTest.pointX); // outputs 16
singletonTest.pointX = 15;
console.log(singletonTest.pointX); // outputs 15
Say Thanks
Respond

1 Response
Add your response

22670
None

Hi, I just upated your example a bit (corrected docs, shortened code, output in textarea instead of console):
http://jsfiddle.net/maxhq/Ltnq1k6j/

Regards,
maxhq

over 1 year ago ·