Singleton Sun

HTML

1. Create Two Sun Instances SunA and SunB
<button onclick="step1()">Step 1</button><br>
2. Check if SunA equals SunB
<button onclick="step2()">Step 2</button><br>
3. Loose mass in SunB by calling emitLight()
<button onclick="step3()">Step 3</button><br>
4. Check again if SunA.mass equals SunB.mass
<button onclick="step4()">Step 4</button><br>

JavaScript

var Sun = (function(){
              var createSun = new function(){
                         var privateMass = 10000000000; //private
                         var looseMass = function(mass){
                             privateMass -= mass;    
                         }
                         var publicEmitLight = function(){
                                  //some complex Nuclear fission 
                                  //calling looseMass()
                                  looseMass(10);
                         };
                         var getMass = function(){
                                  return privateMass;
                         };
                         return {
                                emitLight: publicEmitLight,
                                getMass: getMass
                         };
              };
 
              return {
                    getInstance: createSun
              };
})();

step1 = function(){
    sunA = Sun.getInstance;
    sunB = Sun.getInstance;
    alert('Created two global var SunA and SunB!');
};
step2 = function(){
    alert('sunA === sunB: ' + (sunA === sunB)); //true
};
step3 = function(){
    sunB.emitLight(); //loose some Mass in sunB
    alert('Lost mass in SunB');
};
step4 = function(){
    alert('sunA.getMass() === sunB.getMass(): '+ (sunA.getMass() === sunB.getMass())); //true
};