> For the complete documentation index, see [llms.txt](https://triplexlab.gitbook.io/vanilla-js/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://triplexlab.gitbook.io/vanilla-js/basics/05-function/this.md).

# this의 의미 6개 총정리

## this의 의미 6개 총정리

**여기서는 this의 유효범위(scope)를 확인하는것이 포인트 입니다.**

### 01. this  (**일반(전역)함수에서 this를 사용하는 경우)**

```javascript
<script>
    console.log(this);
    
    function guntion () {
        console.log(this);    
    };
    guntion();
</script>
```

```javascript
// 결과)
window
window
```

### 02. this (오브젝트 내 함수(메소드)에서 사용하는 경우)

```javascript
const 오브젝트 = {
    data: 'SO',
    methods : function(){
        naming : function() {
            console.log(this); //여기서의 this는 naming를 가지고 있는 methods를 뜻함
        } 
    }
}

오브젝트.함수();
```

```javascript
// 결과)
 
{
 methods : function(){
        naming : function() {
            console.log(this); //여기서의 this는 naming를 가지고 있는 methods를 뜻함
        } 
}
```

### 03. this (**arrow function에서 사용하는 경우**)

내부의 this값을 변화시키지 않음 (외부 this값 그대로 재사용가능)!

```javascript
const objects = {
    data: {
        mag : [
            {
                id:1,
                msg: 'Hello JS'
            },
            {
                id:2,
                msg: 'Hello JS2'
            },
            {
                id:3,
                msg: 'Hello JS3'
            }
        ]
    },
    methods(){
        console.log(this);  // 여기서의 this는 objects를 가리킵니다. 
        this.data.mag.forEach(element => {
            console.log(this);    //여기서의 this는 내부의 this값을 변화시키지 않음 (외부 objects를 그대로 가리킵니다.!)
            console.log(element); 
        });
    }
}
```

```javascript
// 결과)
window
```

### 04. this (0**1번과 02번은 같은 이야기인 이유(window의 비밀)** )

**01번과 02번은 똑같은 계념 입니다.**

```javascript
-------------------01.----------------
console.log(this);                // window
    
function guntion () {
    console.log(this);            // window
};
-------------------02.----------------
const 오브젝트 = {
    data: 'SO',
    methods : function(){
        naming : function() {
            console.log(this);     //여기서의 this는 naming를 가지고 있는 methods를 뜻함
        } 
    }
}

```

### 0**5**. this (constructor(생성자)에서 this 사용하는 경우)

```javascript
const 객체 = {}

function 공장() {
    this.이름 = 'kim'  //여기서의 this는 새로 생성되는 오브젝트 (instance)를 뜻한다.
}

const 오브젝트 = new 공장();
console.log(오브젝트)
```

```javascript
// 결과)
공장 {이름: "kim"}
```

### 06. this (**event listener 내에서 사용하는 경우**)

```javascript
document.querySelector('.btn').addEventListener('click', function(e){
    console.log(this);            //.btn를 뜻합니다.
    console.log(e.currentTarget); //.btn를 뜻합니다.
});
```
