반응형
this는 함수를 어떻게 호출하냐에따라 가리키는 대상이 달라진다.
function func(){
if(window === this){
document.write("window === this");
}
}
func();
> window === this
var o = {
func : function(){
if(o === this){
document.write("o === this");
}
}
}
o.func();
> o === this
객체의 소속인 메소드의 this는 메소드를 호출한 객체를 가리킨다. 첫번째 경우는 전역 객체인 window를 넣어주면 함수를 호출할때 window.func();로 두 경우 모두 메소드가 속한 객체를 가리키고 있다.
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를 호출할 경우 this의 값은 window를 가리키고 생성자로 사용될때는 this의 값이 생성될 객체를 가리킨다. 생성자가 실행되기 전까지는 객체는 변수에도 할당될 수 없기 때문에 this가 아니면 객체에 대한 어떠한 작업을 할 수 없기 때문이다.
var obj = {
func : function(){
function func2(){
if(this ==== window){
console.log('this === window');
} else if(tihs === obj){
console.log('this === obj');
}
}
func2();
}
}
obj.func();
> this === window
객체안에 메소드를 만들고 메소드안에 내부함수를 추가하여 this를 넣었다. 결과는 window가 출력이 되었다. 내부함수에서 자신이 속한 객체를 가리키는 this가 필요할 시 보통은 다음과 같이 메소드 내에서 this를 변수에 따로 저장하여 그 변수를 사용하는 방법을 취한다.
var obj = {
func : function(){
var that = this;
function func2(){
if(that ==== window){
console.log('that === window');
} else if(that === obj){
console.log('that === obj');
}
}
func2();
}
}
obj.func();
> that === window
apply 메소드와 call 메소드
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();
func.apply(o);
func.apply(p);
> window
> o
> p
apply를 통해 함수의 this값을 o와 p로 변경하여 함수가 실행된다. apply는 인자로 바인딩할 객체와 해당 함수에 전달할 인자들을 배열로 입력받는다. 반면 call은 배열이 아닌 인자들도 입력받는다는 점이 다르다.
반응형
'Programming > JavaScript' 카테고리의 다른 글
Prototype (0) | 2019.12.22 |
---|---|
상속(inheritance) (0) | 2019.12.21 |
생성자와 new (0) | 2019.12.17 |
함수의 호출 apply (0) | 2019.12.16 |
arguments (0) | 2019.12.16 |