[js] this / 리팩토링(target, function)

ch9eri·2022년 2월 22일
0

JavaScript

목록 보기
4/12

js 야간모드 실습
이 포스팅에서 만든 야간모드 버튼을 페이지 하단에도 만들기 위해 똑같은 코드를 복사하여 붙이면 어떤 일이 일어날까?

똑같은 이름의 버튼이 두개 생기므로 위에 있는 버튼만 정상 작동하게 된다
이러한 문제를 해결하기 위해서 아래에 복사한 코드의 버튼명을 바꾸어주면 된다

하지만 버튼을 여러개 만든다면 이러한 방법은 비효율적이다
따라서 this라는 개념을 도입할 것이다


🖤 this

this의 활용 분야 중 event(ex. onclick) 안에서 실행되는 코드들은 this로 코드가 속해있는 태그를 부르기로 약속함

<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';
  }

이 코드에서

if(document.querySelector('#night_day').value === 'night')

❗️ document.querySelector('#night_day)'
이 부분은 자기 자신을 가리키고 있기 때문에
this로 바꿀 수 있음

❗️ id="night_day"
그리고 index태그도 필요 없어짐

⌨️ 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';
  }
  ">

이 코드를 사용하면 웹페이지 아무 곳이나 몇번이고 사용해도
문제가 발생하지 않는다


📌 프로그래밍을 잘하는 방법
: 중복을 끝까지 제거하자!!!

🖤 리팩토링 - 중복제거

: 코드의 효율적이고 유지보수하기 쉽게 만든다

방법1. target 사용 (중복되는 짧은 코드)

위 코드에서

document.querySelector('body').style.backgroundColor = 'black';
document.querySelector('body').style.color = 'white';

이 부분이 중복이기 때문에 이를 없애줄 것이다

target = document.querySelector('body')
: 중복되는 부분을 target이라고 선언한 후
그 뒤로 중복되는 부분을 다 target으로 바꾼다

<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';
  }
  ">

방법2. 함수 사용 (중복되는 긴 코드)

이 부분이 중복되기 때문에

var target = document.querySelector('body');
  if(this.value === 'night'){
    target.style.backgroundColor = 'black';
    target.style.color = 'white';
    this.value = 'day';

    var alist = document.querySelectorAll('a');
    var i = 0;
    while(i<alist.length){
      alist[i].style.color = 'powderblue';
      i = i+1;
        }
  }
  else{
    target.style.backgroundColor = 'white';
    target.style.color = 'black';
    this.value = 'night';

    var alist = document.querySelectorAll('a');
    var i = 0;
    while(i<alist.length){
      alist[i].style.color = 'blue';
      i = i+1;
        }
  }

이 코드를 잘라내어 head 부분으로 옮겨준 후 함수 선언을 한다.

<head>
<script>
function nightDayHandler(self){

... (중복되는 코드)

}
</script>
</head>
<body>
<input type="button" value="night" onclick="
    nightDayHandler(this);
  ">
</body>

❗️함수 선언
function nightDayHandler(self)

❗️함수 호출
nightDayHandler(this);

마지막으로
함수 선언 내부의 this를 self로 바꾼다
(함수선언을 하면서 this가 가르키는 것이 index에서 전역으로 바뀌기 때문)


📦 nightDayHandler 함수 선언

function nightDayHandler(self){
var target = document.querySelector('body');
  if(self.value === 'night'){
    target.style.backgroundColor = 'black';
    target.style.color = 'white';
    self.value = 'day';

    var alist = document.querySelectorAll('a');
    var i = 0;
    while(i<alist.length){
      alist[i].style.color = 'powderblue';
      i = i+1;
        }
  }
  else{
    target.style.backgroundColor = 'white';
    target.style.color = 'black';
    self.value = 'night';

    var alist = document.querySelectorAll('a');
    var i = 0;
    while(i<alist.length){
      alist[i].style.color = 'blue';
      i = i+1;
        }
  }
}
profile
잘하자!

0개의 댓글