After reading a large number of articles on a singleton template and performing some tests, I did not find the difference between a singleton template 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();
Both of them make only one instance of the object, both of them can have "private" members, that points to the window object in any of them. It is just that the latter is simpler. Please correct me if I am wrong.
Using a 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 using that correctly, but it is not solitary.
My question is: What are the common advantages and disadvantages of these three approaches? (If that matters, I'm working on a web application using Dojo 1.9, so anyway this object will be inside Dojo require ).
source share