# this

## this

**this는 함수 내에서 함수 호출 맥락(context)를 의미한다.** 맥락이라는 것은 상황에 따라서 달라진다는 의미인데 즉 함수를 어떻게 호출하느냐에 따라서 this가 가리키는 대상이 달라진다는 뜻이다.

### 함수호출

```javascript
function func(){
    if(window === this){
        document.write("window === this");
    }
}
func(); //window === this
```

### 메소드의 호출

```javascript
var o = {
    func : function(){ //메소
        if(o === this){
            document.write("o === this");
        }
    }
}
o.func(); //o === this
```

**객체의 소속인 메소드의 this는 그 객체**를 가르킨다.&#x20;

### 생성자의 호출

```javascript
var funcThis = null; 
 
function Func(){
    funcThis = this;
}
var o1 = Func();
if(funcThis === window){
    document.write('window <br />'); // window
}
 
var o2 = new Func();
if(funcThis === o2){
    document.write('o2 <br />'); // o2 
}
//this 생성자가 만든 객체를 갖는다. 
```

###

### apply, call

```javascript
var o = {}
var p = {} 
function func(){ //switch : 값과 같은 것을 만났을때 결과값이 출력됨  break를 만날때까지 반복
    switch(this){
        case o:
            document.write('o<br />');
            break;
        case p:
            document.write('p<br />');
            break;
        case window:
            document.write('window<br />');
            break;          
    }
}
func(); //window 
func.apply(o); // o 
func.apply(p); // p
```

함수의 메소드인 apply, call을 이용하면 this의 값을 제어할 수 있다.

메소드(노예) 는 객체(주인) 에 종속되어 있다.  apply -> 이러한것을 제어 할 수 있다.&#x20;

![](https://810537134-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-MZh1fxUzW3zjggiSfv4%2F-M_G2LsMJtLRbswmp-Th%2F-M_G326PA6MHKM5K-uHA%2Fimage.png?alt=media\&token=2b8d2479-0e40-41e7-b7d6-ab11cd537e8d)
