2015년 11월 5일 목요일

자바스크립트 패턴스


  • 전역변수의 최소화. 필수

  •  var a=b=0; 이면 b 는 전역변수가 된다. <- 안티패턴

  • 암묵적 타입캐스팅 피하기 , 비교는 ===

  • eval() 피하기

  • parseInt 의 두번째 매개변수(진수선택)은 반드시 넣어야 한다. 왜냐면 0으로 시작되는 문자열을 8진수로 오해해서 가져올수 있기때문에. parseInt("06",10); 와 parseInt("06")은 다른거다.

  • javascript 에서는 중괄호는 앞의 명령문과 동일한 행에 두어야 한다. 그렇지 않으면 javascript 엔진에서 해당줄에 자동으로 세미콜론을 삽입하기 때문이다.(한줄 아래에 중괄호 두는 것은 자바스크립트에서는 금지)

  • new Object 로 객체 생성 <- 안티패턴

  • new Array로 배열생성 <- 안티패턴 (권장 : 대괄호로 생성)

  • 배열인지 판별은 Array.isArray(배열) 로 하는것을 권장

  • 설정객체패턴( 인자를 객체로 전달하는 방식)으로 하면 나중에 유지보수가 쉽다. 

  • 커링에 대해서도 이해하자.

  • 클로져로 비공개 멤버 구현가능
    function A(){ var privateValue ='pv'; this.getName=function(){return privateValue;}

  • 체이닝 패턴은 this 를 리턴하면됨.

  • 메쏘드 패턴도 이해하자.

  • 상속방법
    inherit(Child,Parent){ C.prototype = new P();} ...overriding?

  • 디자인패턴



  1. 싱글톤

    //싱글톤객체 즉시실행함수형태

    var Stone = (function(){

    var instance;

    function init() {

    function privateMethod(){

    console.log( "private  메쏘드" );

    }

    var privateVariable = "Private 멤버변수";

    return {

    publicMethod: function () {

    console.log( "public 메쏘드" );

    },

    publicProperty: public 멤버변수"

    };

    }; //init

     

    return {

    // getInstance() 하면 인스턴스가 없다면 생성하고 있다면 인스턴스를 리턴

    // 결국  instance 는 init() 함수 객체를 바라보게 된다.

    getInstance: function () {

    if ( !instance ) {

    instance = init();

    }

    return instance;

    }

    };

    })();

    var s1 = Stone.getInstance();

    var s2 = Stone.getInstance();

    console.log( s1 === s2 ); // true

    //s1.changepublic();

    s1.publicProperty="hey";

    console.log( s2.publicProperty ); // true

  2. factory pattern
    function Pizza_cheeze() {console.log('cheeze');

    }

    function Pizza_pineapple() {

    console.log('pineapple');

    }

    function PizzaFactory(whichStyle) {

    var pizza = this.createPizza(whichStyle);

     

    this.bake(pizza);

    this.boxing(pizza);

     

    return pizza;

    }

    PizzaFactory.prototype.pizzaClass = Pizza_cheeze;

    PizzaFactory.prototype.bake = function(pizza){

    console.log('bake');

    };

    PizzaFactory.prototype.boxing = function(pizza){

    console.log('boxing');

     

    };

    PizzaFactory.prototype.createPizza = function(whichStyle) {

    switch(whichStyle) {

    case 'cheeze':

    this.pizzaClass = Pizza_cheeze;

    break;

    case 'pineapple':

    this.pizzaClass = Pizza_pineapple;

    break;

     

    };

    return new this.pizzaClass;

    };

    var pizzacheeze = new PizzaFactory('cheeze');

    var pizzapineapple = new PizzaFactory('pineapple');

     

  3. Decorator Pattern
    //기본객체
      function Car() {

          console.log('car frame');

          this.price = 1000;


        }


      //가격정보얻기

      Car.prototype.getPrice = function() {

          return this.price;

      };

    //데코레이터 배열

        Car.CarDecorators = {};


      //파워윈도우 옵션질

      Car.CarDecorators.powerWindow = {

          getPrice : function() {

              var price = this._super.getPrice();

             price += price *5 /100;

              return price;

          }

      };

    //
      Car.prototype.decorate = function (decorator) {

          var F = function () {},

          overrides = this.constructor.CarDecorators[decorator],

          i,

          newobj;

          // Create prototype chain

          F.prototype = this;

          newobj = new F();

          newobj._super = F.prototype;

          // Mixin properties/methods of our decorator

          // Overriding the ones from our prototype

          for (i in overrides) {

              if (overrides.hasOwnProperty(i)) {

                  newobj[i] = overrides[i];

              }

          }

          return newobj;

      }

      var car2 = new Car(50);

      car2 = car2.decorate('powerWindow');

      console.log(car2.getPrice()); // outputs $CDN52.50


0 comments:

댓글 쓰기