객체지향 프로그래밍이란 어떤 동작이나 로직보다는 객체를 중심으로 프로그래밍을 하는 일종의 새로운 패러다임이다. 여기서 객체란 우리가 모델링하고자 하는 대상과 관련된 모든 정보와 데이터, 코드, 동작, 기능들을 담을 수 있다. 캡슐화, 추상화, 상속, 다형성 등의 특징이 있다.
함수를 객체화해서 코드의 복잡성을 줄여보도록 하자
templateList
, templateHTML
함수를 template 객체로 만들 수 있다.
var template = {
html: function (title, list, body, control){ //templateHTML
return `
<!doctype html>
<html>
<head>
<title>WEB1 - ${title}</title>
<meta charset="utf-8">
</head>
<body>
<h1><a href="/">WEB</a></h1>
${list}
${control}
${body}
</body>
</html>
`;
},
list: function (filelist){ //templateList
var list = '<ul>';
var i = 0;
while(i < filelist.length){
list = list + `<li><a href="/?id=${filelist[i]}">${filelist[i]}</a></li>`;
i = i + 1;
}
list = list+'</ul>';
return list;
},
}
이제 template.list
, template.html
을 이용해서 이전의 함수를 사용할 수 있게 됨!
수정 예시를 하나 들어보자
if(queryData.id === undefined){
fs.readdir('./data', function(error, filelist){
var title = 'Welcome';
var description = 'Hello, Node.js';
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);
/*var list = templateList(filelist);
var template = templateHTML(title, list, `<h2>${title}</h2>${description}`,
`<a href="/create">create</a>`);
response.writeHead(200);
response.end(template);*/
})