객체지향_2)this

양갱장군·2020년 8월 28일
0

this


this는 함수 내에서 함수 호출 맥락(context)를 의미한다. 따라서 함수를 어떻게 호출하느냐에 따라서 this가 가리키는 대상도 달라진다.

함수호출

  • 함수 호출 시 this는 전역객체인 window와 같다

메소드호출

  • 메소드(객체의 소속)의 this는 해당 메소드가 속한 객체를 가르킨다.
    var o = {
        func : function(){
            if(o === this){
                document.write("o === this");
            }
        }
    }
    o.func();  // 결과 o === this

생성자호출

아래 예문을 통해 함수를 호출했을 때와, 생성자를 호출했을 때의 this값 차이를 발견할 수 있다.

var funcThis = null; 
function Func(){
    funcThis = this;
}
var o1 = Func();
if(funcThis === window){
    document.write('window <br />');
}
var o2 = new Func();
if(funcThis === o2){
    document.write('o2 <br />');
}  // 결과: window, o2

생성자는 빈 객체를 만든다. 그리고 이 객체내에서 this는 만들어진 객체를 가르킨다. 이것은 매우 중요한 사실이다. 생성자가 실행되기 전까지는 객체는 변수에도 할당될 수 없기 때문에 this가 아니면 객체에 대한 어떠한 작업을 할 수 없기 때문이다.

function Func(){
    document.write(o);
}
var o = new Func(); // 결과: undefined

apply,call과 this


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

var o = {}
var p = {}
function func(){
    switch(this){ //swith는 괄호안에 들어간 값과 같은 구간이 실행
        case o:
            document.write('o<br />');
            break;
        case p:
            document.write('p<br />');
            break;
        case window:
            document.write('window<br />');
            break;          
    }
}
func();
func.apply(o);
func.apply(p);

결과

window
o
p

0개의 댓글