> For the complete documentation index, see [llms.txt](https://westsilver.gitbook.io/study-script/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://westsilver.gitbook.io/study-script/javascript/basic/refactoring.md).

# 리팩토링

코드를 개선하여 **중복코드를 낮추어**, 가독성을 높이고 **유지보수를 편리**하게 하는 작업을 의미

## 1. this

> 코드가 속해있는 태그를 가리키도록 약속되어 있는 특수한 키워드 (즉, 자기자신)

{% tabs %}
{% tab title="before" %}

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

{% endtab %}

{% tab title="after" %}

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

{% endtab %}
{% endtabs %}

## 2. target

> 변수선언 :  'target'에 중복되는 태그를 대입

{% tabs %}
{% tab title="before" %}

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

{% endtab %}

{% tab title="after" %}

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

{% endtab %}
{% endtabs %}
