6

After reading a lot of articles on singleton pattern, and making some tests, I found no difference between the singleton pattern like this (http://jsfiddle.net/bhsQC/1/):

var TheObject = function () {
    var instance;

    function init() {
        var that = this;
        var foo = 1;

        function consoleIt() {
            console.log(that, foo);
        }
        return {
            bar: function () {
                consoleIt()
            }
        };
    }
    return {
        getInstance: function () {
            if (!instance) {
                instance = init();
            }
            return instance;
        }
    };
}();
var myObject = TheObject.getInstance();
myObject.bar();

and code like this (http://jsfiddle.net/9Qa9H/3/):

var myObject = function () {
    var that = this;
    var foo = 1;

    function consoleIt() {
        console.log(that, foo);
    }
    return {
        bar: function () {
            consoleIt();
        }
    };
}();
myObject.bar();

They both make only one instance of the object, they both can have "private" members, that points to window object in either of them. It's just that the latter one is simpler. Please, correct me if I'm wrong.

Using standard constructor like this (http://jsfiddle.net/vnpR7/2/):

var TheObject = function () {
    var that = this;
    var foo = 1;

    function consoleIt() {
        console.log(that, foo);
    }
    return {
        bar: function () {
            consoleIt();
        }
    };
};
var myObject = new TheObject();
myObject.bar();

has the advantage of correct usage of that, but isn't a singleton.

My question is: what are the overall advantages and disadvantages of these three approaches? (If it matters, I'm working on a web app using Dojo 1.9, so either way, this object will be inside Dojo's require).

10
  • 1
    Just out of the curiosity why would someone use the singleton pattern in JavaScript? Wouldn't it make sense to use one object like: var obj1 = { } Sorry for offtopic Commented May 21, 2013 at 11:05
  • @KirillIvlev with singleton/module pattern you can have private vars and functions inside the IIFE. The singleton from OP seems to apply lazy loading as well - only instantiate when first called. Commented May 21, 2013 at 11:05
  • I'd rather simply use an auto-invoking function to hide away the constructor, i.e., something like this: jsfiddle.net/qFMcL Commented May 21, 2013 at 12:32
  • I don't really understand why you want that point to window? Commented May 21, 2013 at 13:05
  • Please see this answer by CMS: stackoverflow.com/a/1479341/113083 Commented May 21, 2013 at 13:10

3 Answers 3

3

Well, the real difference is the time of construction of the singleton. The second approach creates the singleton right away, the first only after being called the first time. Depending on what the singleton needs in memory, this might make a difference for your application. For example, you might need the singleton only if a user performs a certain action. So if the user does not do it, then it would be nice not to have to initialise the singleton at all.

Also, if the initialisation of the singleton is computationally intense, it is a good thing to be able to defer that until you really need the singleton.

Edit: And as Jani said, the last one isn't a singleton, so i didn't discuss it.

Sign up to request clarification or add additional context in comments.

2 Comments

Well yes, I missed the obvious - time of construction. In my case it doesn't matter, cause I'm using this sort of as a namespace. That's why I included the third option, because I'm still not sure should I be using singleton at all...
All righty then, i don't see any other significant differences. Regarding wether you should be using a singleton at all, that of course, is a whole other dicussion :)
1

I don't think there's really a big practical difference between the first two.

The first one with getInstance behaves more like a singleton pattern in classical OOP languages like Java.

The second approach behaves more like a static class in classical OOP languages.

Obviously the issues both of these have are the same all singletons have (plenty of material for this if you look it up on google).

The last approach is not really even using new - you're returning an object from the "constructor". Obviously this one is not a singleton at all, and as such, would be the preferred approach.

2 Comments

I'm prepared to be downvoted for this question, but - what are the "issues" of singletons, apart from the that problem? There are lots of questions out there, but I just can't find any good answers.
Here's some good answers on SO regarding that stackoverflow.com/questions/137975/…
0

I like to build singletons likes this:

function FriendHandler(){ 
    if(FriendHandler.prototype.singleton){ 
        return FriendHandler.prototype.singleton; 
    }

    if(!(this instanceOf FriendHandler)){
        return new FriendHandler();
    }

    FriendHandler.prototype.singleton = this;
 ...
    this.selectFriends = function(firstName){
        ...
    };
}

If you do:

new FriendHandler()
or
FriendHandler()

It always returns the same instance.

I wrote about it some months ago: http://franciscomsferreira.blogspot.com/2013/01/how-to-write-maintainable-javascript-or.html

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.