본문 바로가기

Web/CS공부

[JavaScript] this의 상황별 뜻

 

개발을 하다보면 자주 보이고 자주 심란하게 만드는 this키워드

상황별로 각각 가리키는 대상이 다릅니다.

 

 

 

1. 그냥 쓰거나 함수 안에서 쓰는 this는 window를 가리킨다.

// 빈 화면에서
console.log(this); // window

---------------------

// 일반 함수 안에서
function fc(){
	console.log(this); // window
}
fc()

 

 

 

 

2. 오브젝트 내 함수에서 쓰는 this는 현재 위치한 함수의 오브젝트명을 가리킨다.

var Obj = {
	data : 'kim',
    fc : function(){
    	console.log(this); // Obj
        }
    }
}

Obj.fc(); // Obj


-----------------------

var Obj = {
	data : {
    	fc : function() => {
        	consolw.log(this); // fc
        }
    }
}

Obj.data.fc(); // fc

 

 

 

 

3. function이 아닌 arrow함수( ()=> )를  사용할 경우, 함수 밖의 this 값을 가리킨다.

console.log(this) // window

var Obj = {
	data : {
    	fc : () => {
        	console.log(this); // window
        }
    }
}

Obj.data.fc(); // window

 

 

 

 

4. 생성자(Constructor)안에서 쓰면 새로 생성되는 오브젝트(instance)를 가리킨다.

var list = {}

function doc(){ // 생성자(Constructor)
	this.name = 'kim' // 새로 생성되는 오브젝트(instance)
}

var Obj = new doc();

console.log(Obj); // {'name' : 'kim'}

 

 

 

 

5. 이벤트리스너 안에서 쓰는 this는 `e.currentTarget`(해당 이벤트를 동작시킨 요소)가 된다.

<button id='btn'> 버튼 </button>

<script>
	document.getElementById('btn').addEventListner('click',function(){
    	console.log(this);  // <button id='btn'> 버튼 </button>
    })
</script>

 

 

 

 

6. 오브젝트 내에서 콜백함수를 쓰게될 때 this는 window를 가리킨다.

var Obj = {
	names: ['kim', 'lee', 'park'],
    fc : function(){
    	console.log(this); // {names: array(3), fc:𝑓}
    	Obj.names.forEach(function(){
        	console.log(this); // window * 3
        })
    }
}

Obj.fc();

 

728x90