JAVA
20220412 - WEB JavaScript 31
쿠쿠(KOOKOO)
2022. 4. 12. 21:32
- 코딩을 하고 나서 1차 완성된 코드의 비효율적인 부분에 대해
동작하는 것은 그대로 두고 코드를 효율적으로 만들어서 가독성을 높이고 유지보수를 하기 쉽도록 하는 것
(이 개선하는 작업을 리팩토링이라고 한다)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
<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';
}
">
<ol>
<li><a href="1.html">HTML</a></li>
<li><a href="2.html">CSS</a></li>
<li><a href="3.html">JavaScript</a></li>
</ol> ... ... .
|
document.querySelector('#night_day') 이 부분은 사실상 자기 자신을 가리키고 있다.
onclick event가 속해 있는 태그 자신! === this로 대체 가능
if(this.value === 'night')
this로 바꾸면서 id="night_day" 이부분 또한 삭제 가능(인덱스 태그를 참조하는 것은 this로 하면 되기때문)
이렇게 수정한 코드는 무한 복사해서 붙여넣어도 이상없이 잘 작동한다.
#night_day를 정의해주지 않아도 this를 통해 자기 자신을 찾을 수 있기 때문
위 코드의 모든 document.querySelector('#night_day')는 this로 대체하면 된다.
효율적인 코드: 중복을 끝까지 쫓아가서 다 없애버리기!
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
<h1><a href="index.html">WEB</a></h1>
<input 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';
}
">
<ol>
<li><a href="1.html">HTML</a></li>
<li><a href="2.html">CSS</a></li>
<li><a href="3.html">JavaScript</a></li>
</ol> ... ... .
|
var target = document.querySelector('body')
document.querySelector('body') 를 target이라는 변수로 정의함으로써 코드 길이를 줄일 수 있다.
공부 자료: https://opentutorials.org/