[JavaScript 2] 조건문과 리팩터링: 토글(Toggle), this 키워드, 변수 설정
비교 연산자와 조건문
<!--ex4.html-->
<h3>1===1</h3> <!--true-->
<script>
document.write(1===1);
</script>
<h3>1===2</h3> <!--false-->
<script>
document.write(1===2);
</script>
<h3>1<2</h3> <!--true-->
<script>
document.write(1<2);
</script>
<h3>1<1</h3> <!--false-->
<script>
document.write(1<1);
</script>
===, <, >와 같은 연산자가 JS에서의 비교 연산자이다. 특이한 점은 등위 연산자가 ===으로 등호를 3개를 써야한다는 것. (값과 형식까지 일치하는지를 판단)
여기서 나온 true/false라는 불리언(boolean) 값으로 조건문을 만들 수 있다.
<!--ex5.html-->
<h2>Program</h2>
<script>
document.write("1<br>");
document.write("2<br>");
document.write("3<br>");
document.write("4<br>");
</script>
<h2>IF-true</h2> <!--1, 2, 4만 출력-->
<script>
document.write("1<br>");
if (true) {
document.write("2<br>");
} else {
document.write("3<br>");
}
document.write("4<br>");
</script>
괄호 안에 불리언 값으로 true가 들어있기 때문에 if 절만 실행되고 else절의 3은 출력하지 않는다.
토글(Toggle)
이전의 night/day 두 개의 스위치가 아닌, 하나의 스위치가 마치 전등처럼 on/off되게 하는 것을 조건문으로 구현할 거다. 이런 스위치 형식을 토글(toggle)이라 한다.
// 토글 기본 코드
<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';
}
">
document.querySelector()를 활용해 해당 버튼의 id(#night_day)를 설정하고 .value 프로퍼티를 사용해 값에 접근할 수 있다.
조건문 내에 버튼의 value값을 바꾸는 줄까지 넣어야 정확히 토글이 동작한다.
리팩터링(Refactoring)
항상 코드는 다듬고 또 다듬을 필요성이 있다. 코드의 가독성을 높이거나, 유지보수에 편하게 만들거나, 중복을 없애는 등의 개선이 필요한데, 이 작업을 리팩터링(refactoring)이라고 한다.
위의 토글 코드를 리팩터링한다면 무엇이 가능할까? 먼저 저 코드를 두 개 이상 사용할 경우 토글이 제대로 이루어지지 않는다. id는 모든 태그에서 유일하게 하나씩만 존재해야 하는데, 같은 코드를 복붙하면 id가 겹쳐지기 때문.
그렇다고 수십, 수백 개의 같은 코드를 복붙하면서 id를 일일이 바꿀 건가? 그러면 너무 잡일이 많아진다.
또 코드에 document.querySelector()가 너무 중복된다. 중복도 없애보자.
this 키워드
굳이 id를 붙여서 쿼리를 고를 필요가 없다. 각 태그 내에서 해당 태그를 가리키기로 약속된 this 키워드가 있기 때문. this로 코드를 개선하면 이렇게 된다.
// 토글 코드 개선1: this
<input 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';
}
">
this를 사용하니 훨씬 코드가 보기 좋고 짧아졌다. 하지만 쿼리셀렉터가 중복되는게 보기 싫다면?
태그를 변수에 할당
target이라는 변수(variable)에 document.querySelector(‘body’)를 할당해보겠다.
// 토글 코드 개선2: var
<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';
}
">
var target에 대입한 것만으로 더 코드가 보기 쉬워졌다.
출처: [생활코딩!HTML+CSS+자바스크립트 JS편 Chapter 13~18]