this

함수와 this

this는 함수 내에서 함수 호출 맥락(context)를 의미 맥락이라는 것은 상황에 따라서 달라진다는 의미

즉, 함수를 어떻게 호출하느냐에 따라서 this가 가리키는 대상이 달라짐

결과적으로 그 함수가 누구의 소속이냐에 따라서 this의 값은 그 소속, 그 "객체"를 가리킴

1. 함수호출

function func(){
    if(window === this){
        document.write("window === this");
    }
}
func();
// window === this
//this는 전역객체인 window와 같다

2. 메소드의 호출

객체의 소속인 method의 this는 그 객체를 가리킴

var o = {
    func : function(){
        if(o === this){
            document.write("o === this");
        }
    }
}
o.func();  
//o === this (o === window.o)

3. 생성자의 호출

함수를 호출했을 때와 new를 이용해서 생성자를 호출했을 때의 차이

var funcThis = null; 
function Func(){
    funcThis = this;
}
var o1 = Func();
if(funcThis === window){
    document.write('window <br />'); 
} //window
 
var o2 = new Func(); // 이 코드에서 this는 만들어진 o2객체
if(funcThis === o2){
    document.write('o2 <br />');
} //o2

3-1. 생성자를 만들기 전에 함수를 실행했을 때?

생성자는 빈 객체를 만듦 그리고 이 객체 내에서 this는 만들어진 객체를 가리킴 (생성자가 실행되기 전까지는 객체는 변수에도 할당될 수 없기 때문에 this가 아니면 객체에 대한 어떠한 작업을 할 수 없기 때문)

function Func(){
    document.write(o); //생성자가 실행되기 전이라서 아직 o는 객체가 아님
}
var o = new Func();
//undefined

4. apply, call을 이용한 this의 값 제어

var o = {}
var p = {}
function func(){
    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

Last updated