JavaScript 디자인 모델 의 템 플 릿 방법 모델 원리 와 용법 예시

본 고 는 JavaScript 디자인 모델 의 템 플 릿 방법 모델 원리 와 용법 을 실례 로 서술 하 였 다.여러분 께 참고 하도록 공유 하 겠 습 니 다.구체 적 으로 는 다음 과 같 습 니 다.
1.템 플 릿 방법 모델:계승 만 사용 하면 실현 할 수 있 는 매우 간단 한 모델 이다.
2.템 플 릿 방법 모델 은 두 부분 으로 구성 되 고 첫 번 째 부분 은 추상 적 인 부류 이 며 두 번 째 부분 은 구체 적 인 실현 부류 이다.
3.디자인 모델 중의 Coffee or Tea 로 모델 링 방법 모델 을 설명 한다.
1.템 플 릿 Brverage,코드 는 다음 과 같 습 니 다.

var Beverage = function(){};
Beverage.prototype.boilWater = function(){
  console.log('    ');
};
Beverage.prototype.pourInCup = function(){
  throw new Error( '      pourInCup' );
};
Beverage.prototype.addCondiments = function(){
  throw new Error( '      addCondiments  ' );
};
Beverage.prototype.customerWantsConditions = function(){
  return true; //      
};
Beverage.prototype.init = function(){
  this.boilWater();
  this.brew();
  this.pourInCup();
  if(this.customerWantsCondiments()){
    //      true,     
    this.addCondiments();
  }
};

2.자녀 상속 부류

var CoffeeWithHook = function(){};
CoffeeWithHook.prototype = new Beverage();
CoffeeWithHook.prototype.brew = function(){
  console.log('       ');
};
CoffeeWithHook.prototype.addCondiments = function(){
  console.log('     ');
};
CoffeeWithHook.prototype.customerWantsCondiments = function(){
 return window.confirm( '       ?' );
};

3.커피 한 잔 끓 이기

var coffeeWithHook = new CoffeeWithHook();
coffeeWithHook.init();

넷 째,다른 문법

var Beverage = function( param ){
  var boilWater = function(){
   console.log( '    ' );
  };
  var brew = param.brew || function(){
   throw new Error( '    brew  ' );
  };
  var pourInCup = param.pourInCup || function(){
    throw new Error( '    pourInCup  ' );
  };
  var addCondiments = param.addCondiments || function(){
   throw new Error( '    addCondiments  ' );
  };
  var F = function(){};
  F.prototype.init = function(){
   boilWater();
   brew();
   pourInCup();
   addCondiments();
  };
  return F;
};
var Coffee = Beverage({
  brew: function(){
     console.log( '       ' );
  },
  pourInCup: function(){
    console.log('       ');
  },
  addCondiments: function(){
    console.log('     ');
  }
});
var coffee = new Coffee();
coffee.init();

위 코드 는 온라인 HTML/CSS/JavaScript 코드 실행 도 구 를 사용 합 니 다http://tools.jb51.net/code/HtmlJsRun테스트 실행 결과:

더 많은 자 바스 크 립 트 관련 내용 은 본 사이트 의 주 제 를 볼 수 있 습 니 다.,,,,,,,,,,,,,,,
본 고 에서 말 한 것 이 여러분 의 자 바스 크 립 트 프로 그래 밍 에 도움 이 되 기 를 바 랍 니 다.

좋은 웹페이지 즐겨찾기