1. 단독으로 this를 호출 한 경우는 global object를 가리킴 - window{...}
console.log(this)
2. 함수 안에서 호출 한 this도 window객체에 바인딩
function myFnc() {
console.log(this);
}
myFnc();
3. strict mode일 때 함수 안에서 쓰면 this는 undefined
<script>
'use strict';
function myFnc(){
console.log(this);
}
myFnc();
</script>
4.오브젝트 자료형 안에 있는 함수(오브젝트안의 메소드)의 this는 함수를 갖고 있는 바로 위의 오브젝트를 가리킴
console.log(this)
var obj1 = {
data : 'Kim',
myFnc : function(){ console.log(this) }
}
obj1.myFnc();
var obj1 = {
data : 'Kim',
obj2 : {
data : 'Pack',
myFnc : function(){ console.log(this) }
}
}
obj1.obj2.myFnc();
4-2 아까 위의 "2. 함수 안에서 호출 한 this도 window객체에 바인딩" 이라는 내용도 결국 window라는 커다란 오브젝트 안에 있는거니까
window : {
function myFnc() {
console.log(this);
}
myFnc();
}
5.Arrow Function은 this 값을 함수 스코프 바로 밖깥에 있는 상위 함수의 this를 가져오거나, 상위 class에서 값을 물려받음
console.log(this)
var obj1 = {
data : 'Kim',
obj2 : {
data : 'Pack',
myFnc : ()=>{ console.log(this) }
}
}
obj1.obj2.myFnc();
6.이벤트핸들러, 이벤트리스너 안에서의 this는 바인딩 된 HTML DOM요소를 가리킴(this == e.currentTarget )
<button id="btn">버튼</button>
document.getElementById('btn').addEventListener('click', function(e){
console.log(this);
console.log(e.currentTargaet);
7.생성자 안에서의 this는 생성자 함수가 생성하는 객체로 this가 바인딩
function Person(name) {
this.name = name;
}
var kim = new Person('kim');
console.log(kim.name);