JavaScript singleton pattern and 'this' -
after reading lot of articles on singleton pattern, , making tests, found no difference between singleton pattern (http://jsfiddle.net/bhsqc/1/):
var theobject = function () { var instance; function init() { var = 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 (http://jsfiddle.net/9qa9h/3/):
var myobject = function () { var = this; var foo = 1; function consoleit() { console.log(that, foo); } return { bar: function () { consoleit(); } }; }(); myobject.bar();
they both make 1 instance of object, both can have "private" members, that
points window
object in either of them. it's latter 1 simpler. please, correct me if i'm wrong.
using standard constructor (http://jsfiddle.net/vnpr7/2/):
var theobject = function () { var = this; var foo = 1; function consoleit() { console.log(that, foo); } return { bar: function () { consoleit(); } }; }; var myobject = new theobject(); myobject.bar();
has advantage of correct usage of that
, isn't singleton.
my question is: what overall advantages , disadvantages of these 3 approaches? (if matters, i'm working on web app using dojo 1.9, either way, object inside dojo's require
).
well, real difference time of construction of singleton. second approach creates singleton right away, first after being called first time. depending on singleton needs in memory, might make difference application. example, might need singleton if user performs action. if user not it, nice not have initialise singleton @ all.
also, if initialisation of singleton computationally intense, thing able defer until need singleton.
edit: , jani said, last 1 isn't singleton, didn't discuss it.
Comments
Post a Comment