[JavaScript]/[JavaScript] 공부 기록
[JS 공부] WEB2 JS - 16~18강_조건문,리팩토링 중복제거(this, var변수)_230419(수)
노트포미
2023. 4. 19. 19:16
https://youtube.com/playlist?list=PLuHgQVnccGMBB348PWRN0fREzYcYgFybf
WEB2-JavaScript
www.youtube.com
[16강] 조건문
[강의 내용]
- 조건문 if, else
if(조건문){
...조건문이 true일 경우 실행될 코드...
}else{
...조건문이 false일 경우 실행될 코드...
}
[새로 알게 된 내용]
- 글 태그 안에 <br>을 사용하면 개행됨
<h1>JavaScript</h1> //-> JavaScript
<h1>Java<br>Script</h1> //-> Java
Script
[17강] 조건문의 활용
[실습 내용]
: day모드에서는 버튼을 누르면 night모드로 변경되고,
night모드에서는 버튼을 누르면 day모드로 변경되도록 하기.
* 버튼은 한개
* 버튼의 value값으로 조건문 사용하기
* 처음은 day모드로 시작
[코드]
<body>
<input type="button" id="theme" value="night" onclick="
if(document.querySelector('#theme').value === 'night'){
document.querySelector('body').style.backgroundColor='black';
document.querySelector('body').style.color='white';
document.querySelector('#theme').value = 'day';
}else{
document.querySelector('body').style.backgroundColor='white';
document.querySelector('body').style.color='black';
document.querySelector('#theme').value = 'night';
}
">
<h1>JavaScript</h1>
</body>
[결과]
JavaScript
[18강] 리팩토링 중복의 제거
- 리팩토링(refactoring) : 코드의 구조, 관계를 단순화 하여 가독성, 유지보수성을 높이는 기법
ex) 중복제거
<리팩토링 도구>
1. this
: 호출한 본인을 지시함
//this를 사용하지 않을 때
<input type="button" id="theme" value="night" onclick="
document.querySelector('#theme').value = 'day';
">
//this를 사용할 때
<input type="button" value="night" onclick="
this.value = 'day';
">
=> 외부적으로는 같은 행동을 하지만, 내부적으로 훨씬 단순화 됨
* 기존처럼 id를 사용하면, 복사붙여넣기로 같은 버튼을 만들 때 새로운 id를 지정해줘야함
but, 'this'를 사용할 경우 복사붙여넣기해도 오류없이 가능
//this를 사용하지 않을 때
<input type="button" id="theme" value="night" onclick="
document.querySelector('#theme').value = 'day';
">
<input type="button" id="theme2" value="night" onclick="
document.querySelector('#theme2').value = 'day';
">
=> id='theme' / id='theme2'로 다르게 정해줘야함
//this를 사용할 때
<input type="button" value="night" onclick="
this.value = 'day';
">
<input type="button" value="night" onclick="
this.value = 'day';
">
=> 동일하게 복붙 가능
2. 변수사용
var 변수이름 = 중복되는 값;
//변수를 사용하지 않을 때
document.querySelector('body').style.backgroundColor='black';
document.querySelector('body').style.color='white';
=> document.querySelector('body')처럼 긴 문장이 반복됨
//변수를 사용할 때
var target = document.querySelector('body);
target.style.backgroundColor='black';
target.style.color='white';
=> document.querySelector('body')를 target 으로 간편하게 나타낼 수 있음