Javascript singleton class default value -
how can set default value in singleton class. have dictionary in class variable name "myvar" assigned value of 3. however, running code below not return value of 3, instead returns undefined.
init = function() { var var1 = singleton.myvar; console.log(var1); // returns undefined var1 = 3; console.log(var1);; // returns 3 var var2 = singleton.myvar; console.log(var2); // returns undefined }
singleton class:
var singleton = (function(){ var instantiated; function init (){ // singleton code goes here return { myvar: 3, publicwhatever:function(){ alert('whatever') }, publicproperty:2 } } return { getinstance :function(){ if (!instantiated){ instantiated = init(); } return instantiated; } } })()
you need use getinstance
function singleton instance :
var var1 = singleton.getinstance().myvar;
note factory seems overly complicated. see point in using an iife (you define additional private fields or functions) use iife , reduce singleton factory to
var singleton = (function(){ return { myvar: 3, publicwhatever:function(){ alert('whatever') }, publicproperty:2 } })();
Comments
Post a Comment