Williammer
4/1/2015 - 2:57 PM

implement a singleton klass with redefine constructor pattern and IIFE.

implement a singleton klass with redefine constructor pattern and IIFE.

// Constructor way
function SingletonKlass() {
    var instance;
    
    SingletonKlass = function SingletonKlass() {
        return instance;
    }
    
    SingletonKlass.prototype = this;
    instance = new SingletonKlass();
    instance.constructor = SingletonKlass;
    
    // properties.
    instance.createdTime = 0;
    instance.getRandNum = Math.random();
    
    return instance;
}

// IIFE way
var SingletonKlass;
 
(function() {
    var instance;
    
    SingletonKlass = function SingletonKlass() {
        if(instance){
            return instance;
        }
        
        instance = this;
        
        // properties.
        instance.createdTime = 0;
        instance.getRandNum = Math.random();
    };
}());