리팩토링(Refactoring)이라는 것은
re 다시 factory 공장에 보낸다
공장으로 다시 보내서 좀 더 개선한다, 이런 느낌으로 생각하면 된다.
비효율적으로 코드를 효율적으로 만들어서
가독성을 높이고, 유지보수를 하기 편하게 만들고, 중복된 코드를 낮추는 이러한
방향으로 코드를 다시 개선하는 작업을 리팩토링이라고 한다.
<input id="night_day" type="button" value="night" onclick="
if(document.querySelector('#night_day').value === 'night'){
document.querySelector('body').style.backgroundColor = 'black';
document.querySelector('body').style.color = 'white';
document.querySelector('#night_day').value = 'day';
} else {
document.querySelector('body').style.backgroundColor = 'white';
document.querySelector('body').style.color = 'black';
document.querySelector('#night_day').value = 'night';
}
">
만약에 저 버튼을 다른 곳에도 넣고 싶어서 코드를 그대로 복사 붙여넣기 하면
night_day라는 id가 중복되버려서 제대로 작동하지 않는다.
night_day2이런식으로 id를 바꿔야지만 작동한다.
이것은 너무 불편하고 손이 많이 가니 좀 더 효율적으로 바꿔보자.
See the Pen 리팩토링 by egoing (@egoing) on CodePen.
이 코드가 속해 있는 태그는 input태그다.
그 태그를 가리키도록 약속되어 있는 특수한 키워드가 있는데 바로
this다.
그러면 id="night_day"를 지우고 document.querySelector('#night_day')를 this로 바꿔주면 된다.
이렇게하면 다른 곳에 이 버튼을 넣고 싶으면 그냥 복사 붙여넣기 하면 된다.
///////////////////////////////////////////
document.querySelector('body')라고 되어 있는 부분이 중복해서 등장하고 있다.
이 중복을 없애기 위해서 target이라는 변수를 만들고
var target = document.querySelector('body');
document.querySelector('body')을 target으로 대체한다.
그러면 코드의 양이 줄었고 target만 바꾸면 target변수를 사용하는 모든 코드가 한 번에 변하는
폭발적인 효과를 갖게 된다.
'JScript > Today I learned' 카테고리의 다른 글
TIL#07 객체 (0) | 2021.05.09 |
---|---|
TIL#06 함수(매개변수,인자,리턴) (0) | 2021.05.09 |
TIL#05 배열과 반복문 (0) | 2021.05.09 |
TIL#03 조건문 ,비교연산자, 불리언(Boolean) (0) | 2021.05.09 |
TIL#01 생활코딩 JavaScript (0) | 2021.05.08 |