logo
Search검색어를 포함하는 게시물들이 최신순으로 표시됩니다.
    Table of Contents
    [JS] 2.2. Refactoring

    이미지 보기

    [JS] 2.2. Refactoring

    • 22.02.06 작성

    • 읽는 데 3

    TOC

    참고 자료

    boostcourse 생활코딩: 자바스크립트의 시작


    Refactoring

    중복되는 코드를 줄여 더 간결하고 효율적으로 코드를 짜는 것. 가독성이 좋아지고 유지보수에 편리하다.


    Refactoring 실습

    <body style="color: black; background-color: white;">
      <input
        id="night_day"
        type="button"
        value="night"
        onclick="
        if(document.querySelector('#night_day').value === 'night'){
          document.querySelector('body').style.color='white';
          document.querySelector('body').style.backgroundColor='black';
          document.querySelector('#night_day').value = 'day';
        } else {
          document.querySelector('body').style.color='black';
          document.querySelector('body').style.backgroundColor='white';
          document.querySelector('#night_day').value = 'night';
        }
      "
      />
    
      <ul>
        <li .list="">내용</li>
        <li .list="">내용</li>
        <li .list="">내용</li>
      </ul>
    </body>
    

    기존의 비효율적인 코드이다. 이를 리팩토링해보자.


    1. this

    어떠한 태그 내에서 이벤트에 대한 동작을 할 때 태그 자신을 변경하거나 조작해야한다면, this를 활용한다.

    위의 코드에서 document.querySelector('#night_day')는 태그 자신이다. 이를 this로 바꾼다. 그리고 this를 사용하면 id명을 통해서 태그를 찾을 필요가 없기 때문에 id 부분은 제거해줘도 된다. 리팩토링의 결과는 다음과 같다.

    <input
      type="button"
      value="night"
      onclick="
        if(this.value === 'night'){
          document.querySelector('body').style.color='white';
          document.querySelector('body').style.backgroundColor='black';
          this.value = 'day';
        } else {
          document.querySelector('body').style.color='black';
          document.querySelector('body').style.backgroundColor='white';
          this.value = 'night';
        }
      "
    />
    

    나의 생각

    일단 그동안 해오던대로 document.querySelector('#night_day')로 문서(document) 전체에서 night_day라는 id를 가진 태그를 찾아 값을 지정하는 방식은 document 내의 어떠한 태그든 지정할 수 있다는 장점이 있기 때문에 상황에 맞춰 잘 사용하면 되겠다.

    다만 자기 자신을 바꾸는 일이 많다면 this를 적극 활용하면 되겠다.


    2. 변수 지정

    document.querySelector('body') 역시 4번이나 반복된다. 이를 변수에 저장해서 코드를 리팩토링해보겠다.

    <input
      type="button"
      value="night"
      onclick="
        var target = document.querySelector('body')
        if(this.value === 'night'){
          target.style.color='white';
          target.style.backgroundColor='black';
          this.value = 'day';
        } else {
          target.style.color='black';
          target.style.backgroundColor='white';
          this.value = 'night';
        }
      "
    />
    

    훨씬 간결해진 것을 알 수 있다.

    profile

    FE Developer 박승훈

    노력하는 자는 즐기는 자를 이길 수 없다