본문 바로가기

프론트엔드/js

[생활코딩 WEB2 JS 18강] 코딩 잘하는법? 중복 제거하기! 리팩토링

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <h1><a href="index.html">WEP</a></h1>
   
    <input
      type="button"
      value="다크모드"
      onclick="
      var target = document.querySelector('body')
    if(this.value ==='다크모드')
    {
    target.style.backgroundColor = 'black';
    target.style.color = 'white';
    this.value='아침모드';
   
    } else {
    target.style.
    backgroundColor = 'white';
    target.style.
    color = 'black';
    this.value='다크모드';

    }"
    />

    <ol>
      <li><a href="1.html">HTML</a></li>
      <li><a href="2.html">CSS</a></li>
      <li><a href="3.html">JavaScript</a></li>
    </ol>
    <h2>JavaScript</h2>
    <p>이것이 자바다.</p>


    <input
    type="button"
    value="다크모드"
    onclick="
    var target = document.querySelector('body')
    if(this.value ==='다크모드')
    {
    target.style.backgroundColor = 'black';
    target.style.color = 'white';
    this.value='아침모드';
   
    } else {
    target.style.
    backgroundColor = 'white';
    target.style.
    color = 'black';
    this.value='다크모드';
  }
    "
    />


   
  </body>
</html>

 

 

생코 선생님 댓글 중 아주 잘 정리해놓은 것이 있어서 발췌해 옴

18강. 리팩토링, 중복의 제거

[목적] 리팩토링(ReFactoring. 코드의 비효율적인 것을 제거하는 것.

중복코드를 개선하는 등 코드를 깔끔히 정리해주는 것.)을 통해 코드의 중복을 제거한다.

 

[실습

] 16강에서 했던 조건문을 좀 더 깔끔히 바꾸어본다.

(1) <input type="button" value="night" onclick=" -> input 태그 안에 id값을 지정해준 것을 삭제한다.

굳이 안 써도 대체 가능.

 

(2) if(this.value === 'night'){ -> 현재 value값이 night이므로

this로 값을 써주기만 하면 됨. if 안에 있는 코드가 사실상 자기 자신이므로 this를 쓴 것.

 

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

-> value값 써주는 곳은 다 this로 표현.

 

(4) 그런데 여기서 document.querySelector('body')가 계속 중복으로 나오므로

var target = document.querySelector('body')으로 target 변수를 지정해서 더 짧은 코드로 완성 가능.

이 target변수는 input태그 안에서만 유효한 변수.

 

[코드]

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

} ">

 

cf) ctrl+D를 누르면 같은 문자열을 중복 선택해준다. (하나씩 추가되는 형태)

Ctrl+Shift+L을 누르면 커서가 위치된 문자열을 전부 선택해 준다