소프트웨어/JavaScript
[JavaScript] 중복 제거를 위한 refactoring - 야간모드 예제 코드 간결하게
정보통신 고심이
2023. 1. 31. 17:25
오늘은 코드의 중복된 부분을 제거하여 수정을 편하게 하는 방법인 refactoring에 대해 배웠다.
요즘 배우고 있는 코드는 짧고 간결하지만, 코드가 더 길어질 경우 중복된 부분이 많으면 수정하는 과정이 번거롭다.
이전에 작성한 코드이다.
1. 코드를 보면 만약 버튼의 개수가 여러개로 늘어났을 때 id값인 night_day를 수정할 과정이 번거로울 것이다.
2. document.querySelector도 여러번 반복되고 있다.
<body>
<h1><a href="index.html">WEB</a></h1>
<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';
}
">
</body>
1번 문제를 해결 하는 방법은 onclick과 같은 이벤트 안에서 실행되는 코드는 현재 코드가 속해 있는 태그를 가리키도록 약속돼 있는 특수한 키워드(this)를 사용하는 것이다.
document.querySelector('night_day')를 this로 변경한다.
<input id ="night_day" type="button" value="night" onclick="
if (this.value ==='night'){
document.querySelector('body').style.backgroundColor='black';
document.querySelector('body').style.color='white';
this.value ='day';
}
else {
document.querySelector('body').style.backgroundColor='white';
document.querySelector('body').style.color='black';
this.value ='night';
}
2번 문제를 해결 하는 방법은 <body> 태그를 target 변수에 할당하는 것이다.
var target = document.querySelector('body');
해당 코드를 추가한 뒤 documetn.querySelector('body') -> target 으로 변경하면 된다.
<body>
<h1><a href="index.html">WEB</a></h1>
<input id ="night_day" type="button" value="night" onclick="
var target = document.querySelector('body');
if (this.value ==='night'){
target.style.backgroundColor='black';
target.style.color='white';
this.value ='day';
}
else {
target.style.backgroundColor='white';
target.style.color='black';
this.value ='night';
}
">
</body>