如何在我的单例类中设置默认值。我在我的类中有这本字典,其中变量名“myVar”被赋值为 3。但是,在下面运行此代码不会返回值 3,而是返回未定义。
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
}
单例类:
var Singleton = (function(){
var instantiated;
function init (){
// all singleton code goes here
return {
myVar: 3,
publicWhatever:function(){
alert('whatever')
},
publicProperty:2
}
}
return {
getInstance :function(){
if (!instantiated){
instantiated = init();
}
return instantiated;
}
}
})()