# structure

## jQuery 구조

jQuery는 Javascript 기반의 라이브러리이므로 코드가 Javascript로 구성되어 있다.&#x20;

실 코드는 복잡하기 때문에 이해하기 쉽게 구조를 변경하여 원리를 살펴본다.

## 기본 구조

```javascript
function jQuery(selector) {

}
```

jQuery라는 이름의 함수가 있다고 가정해보자. 이 함수는 value를 전달받아 다음 작업을 수행한다.

* value가 string이면 모든태그를 선택하여 저장
* value가 string이 아닐 경우 태그 객체로 간주하고 저장

```javascript
function jQuery(value) {
    const tags = typeof value === "string" ? 
            document.querySelectorAll(value) : [value];
    return tags;
}
```

이 함수는 다음과 같이 호출할 수 있다.

```javascript
jQuery("h1")
```

## 기능 추가

이제 선택된 태그들에 사용할 수 있는 여러 명령들을 추가하여 반환한다.

```javascript
function jQuery(value) {
    const tags = typeof value === "string" ? 
          document.querySelectorAll(value) : [value];
    //글자 색상을 변환하는 기능
    tags.fontColor = function(color){
        for(let i=0; i < this.length; i++) {
            this[i].style.color = color;
        }
        return this;
    };
    //배경 색상을 변환하는 기능
    tags.backgroundColor = function(color) {
        for(let i=0; i < this.length; i++) {
            this[i].style.backgroundColor = color;
        }
        return this;
    };
    return tags;
}
```

추가한 함수는 실제 jQuery와 무관한 기능들이며, 사용은 다음과 같이 한다.

```javascript
jQuery("h1").fontColor("red").backgroundColor("yellow");
```

내부적으로 선택된 요소들을 반복하며 작업을 처리한다.

{% embed url="<https://codepen.io/hiphop5782/pen/XWYEgGE>" %}

## 명칭 간소화

jQuery라는 명칭은 너무 길기 때문에 다음과 같이 간소화한다.

```javascript
window.$ = jQuery;
```

`$`는 `_`와 함께 자바스크립트에서 사용 가능한 특수문자이다. 이를 활용해 명칭을 간소화 할 수 있지만, 다른 라이브러리와 충돌의 가능성이 있다.

최종 코드는 다음과 같아진다.

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

```javascript
$("h1").fontColor("blue").backgroundColor("yellow");
```

{% endtab %}

{% tab title="jQuery" %}

```javascript
function jQuery(value) {
    const tags = typeof value === "string" ? 
          document.querySelectorAll(value) : [value];
    //글자 색상을 변환하는 기능
    tags.fontColor = function(color){
        for(let i=0; i < this.length; i++) {
            this[i].style.color = color;
        }
        return this;
    };
    //배경 색상을 변환하는 기능
    tags.backgroundColor = function(color) {
        for(let i=0; i < this.length; i++) {
            this[i].style.backgroundColor = color;
        }
        return this;
    };
    return tags;
}

window.$ = jQuery;
```

{% endtab %}

{% tab title="HTML" %}

```markup
<h1>Hello jQuery 1</h1>
<h1>Hello jQuery 2</h1>
<h1>Hello jQuery 3</h1>
```

{% endtab %}
{% endtabs %}

{% embed url="<https://codepen.io/hiphop5782/pen/ExREXBp>" %}

## 이벤트 추가

이벤트도 다음과 같이 추가할 수 있다.

```javascript
function jQuery(value) {
    const tags = typeof value === "string" ? 
                document.querySelectorAll(value) : [value];
    //(생략)
    tags.click = function(callback) {
        for(let i=0; i < this.length; i++) {
            this[i].addEventListener("click", callback);
        }
    };
    return tags;
}

window.$ = jQuery;
```

이벤트 설정은 다음과 같이 축약하여 사용할 수 있다.

```javascript
$("h1").click(function(){
    $(this).fontColor("blue").backgroundColor("yellow");
});
```

{% embed url="<https://codepen.io/hiphop5782/pen/xxzWLde>" %}

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

```javascript
$("h1").click(function(){
    $(this).fontColor("blue").backgroundColor("yellow");
});
```

{% endtab %}

{% tab title="jQuery" %}

```javascript
function jQuery(value) {
    const tags = typeof value === "string" ? 
                document.querySelectorAll(value) : [value];
    //글자 색상을 변환하는 기능
    tags.fontColor = function(color){
        for(let i=0; i < this.length; i++) {
            this[i].style.color = color;
        }
        return this;
    };
    //배경 색상을 변환하는 기능
    tags.backgroundColor = function(color) {
        for(let i=0; i < this.length; i++) {
            this[i].style.backgroundColor = color;
        }
        return this;
    };
    tags.click = function(callback) {
        for(let i=0; i < this.length; i++) {
            this[i].addEventListener("click", callback);
        }
    };
    return tags;
}

window.$ = jQuery;
```

{% endtab %}

{% tab title="HTML" %}

```markup
<h1>Hello jQuery 1</h1>
<h1>Hello jQuery 2</h1>
<h1>Hello jQuery 3</h1>
```

{% endtab %}
{% endtabs %}

## 결론

실제 jQuery 코드는 이보다 더 복잡하게 구성되어 있다. 하지만 예시를 통해 jQuery가 추구하는 간소화가 무엇인지 이해할 수 있는 계기가 되었으면 한다.
