less than 1 minute read

17 Node.js - App 제작 - 템플릿 기능 정리정돈하기

객체란?
서로 연관된 데이터와 그 데이터를 처리하는 방법인 함수를 그룹핑해서 코드의 복잡성을 낮추는 수납상자 같은 것.

지금까지 만든 main.js의 함수 templateHTML, templateList
서로 성격이 같은 것들을 그룹핑하기 위하여 접두사가 같은 이름을 사용한다.

이름보다 객체를 통해 정리정돈 할 수 있다.

객체 생성 property 추가 (객체에 있는 값 하나하나를 property라고 한다.)

//html이 프로퍼티이다.
var template = {
  html:function(){
  },
  list:function(){
  }
}
html과 list라는 함수의 이름을 갖고 있는 하나의 객체를 만들어 template라는 이름을 줬다.

function templateHTML(title, list, body, control){}
function templateList(filelist){}

기존의 함수 내용을 이름없는 함수로 붙여넣기 한다.

홈페이지 구현 부분
기존의 코드
var list = templateList(filelist);
          var template = templateHTML(title, list,
            `<h2>${title}</h2>${description}`,
            `<a href="/create">create</a>`
          );

          response.writeHead(200);
          response.end(template);

수정
//templateList,HTML은 객체가 되었기 때문에 template. 으로 접근한다.
          var list = template.list(filelist);
          var html = template.html(title, list,
            `<h2>${title}</h2>${description}`,
            `<a href="/create">create</a>`
          );

          response.writeHead(200);
          response.end(html);

파일만 있던 상황에서 폴더가 생긴 것과 같다.

이전과 기능은 동일하면서 내부의 코드를 효율적으로 바꾸는 행위를 리팩토링Refactoring 이라 한다.