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
).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With