반응형
코드의 가독성을 높이고, 유지보수 하기 편리하도록 만들고, 중복된 코드를 제거하는 방향으로 코드를 다시 효율적으로 개선하는 작업
<!--기존-->
<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';
}
">
<!--변경-->
var target = document.querySelector('body');
<input type="button" value="night" onclick="
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';
}
">
id="night_day"와 document.querySelector('#night_day')는 this를 사용하여 보다 효율적인 운영이 가능하다.
document.querySelector('body')의 중복을 target을 설정하여 제거 -> 이제 target을 변경하면 코드 속의 모든 target이 동시에 바뀐다.
※생활코딩 > WEB > WEB2 - JavaScript 강의를 통해 공부한 내용입니다.
반응형
'프로그래밍 언어 & 데이터베이스 > JavaScript' 카테고리의 다른 글
반복문(Loop) (0) | 2020.08.15 |
---|---|
배열(Array) (0) | 2020.08.06 |
조건문 (0) | 2020.07.11 |
비교 연산자와 Boolean 데이터 타입 (0) | 2020.07.11 |
프로그램, 프로그래밍, 프로그래머 (0) | 2020.07.11 |
댓글