JavaScript Design Pattern

Words
12
Reading
1 min
Listen
Play
8y

Method

(function() {
    //  private 변수들과 함수들 선언
    
    return {
        //  public 변수들과 함수들을 선언
    }
    
})();

Revealing Method

var Exposer = (function() {
    var privateVariable = 10;
    
    var privateMethod = function() {
        privateVariable++;
    }
    
    var methodToExpose = function() {
        
    }
    
    var otherMethodIWantToExpose = function() {
        privateMethod();
    }
    
    return {
        first: methodToExpose,
        second: otherMethodIWantToExpose
    };
})();

Exposer.first();
Exposer.second();
Exposer.methodToExpose;

Singleton

var singleton = (function() {
  var instance;
    function initiate() {
      return {
        a:function(){},
        b:function(){}
      };
    };
    
    return {
        getInstance: function() {
            if (!instance) {
                instance = initiate();
            }
            return instance;
        }    
    };
})();

var first = singleton.getInstance();
var second = singleton.getInstance();

console.log(first == second); //true

Prototype

var car = function() {
    this.numWheels = 4;
    this.manufacturer = '현대';
    this.make = '그랜져';
}

car.prototype.go = function() {
    
}

car.prototype.stop = function() {
    
}

Revealing Prototype

var car = function() {
    this.numWheels = 4;
    this.manufacturer = '현대';
    this.make = '그랜져';
}

car.prototype = function() {
    var go = function() {
        
    };
    
    var stop = function() {
        
    }
    
    return {
        pressBrakePedal: stop,
        pressGasPedal; go
    }
}();
JavaScript Design Pattern | Ecency