그냥 쓰거나 함수 안에서 쓰면 this는 window
그냥 쓰면
console.log(this)
👉 this 키워드는 그냥 window {어쩌구}
함수에서 쓰면
function 함수(){
console.log(this)
}
함수();
👉 똑같이 window {어쩌구}
strict mode일 때 함수 안에서 쓰면 this는 undefined
'use strict'
function 함수(){
console.log(this)
}
함수();
👉 undefined
var 오브젝트 = {
data : 'kim',
함수 : function(){
console.log(this)
}
}
오브젝트.함수();
👉 { data : 'Kim', 함수 : ƒ }
그냥 만든 오브젝트, 그래서 메소드안에서 this를 쓰면 this는 메소드를 가지고 있는 오브젝트
var 오브젝트 = {
data : {
함수 : function(){
console.log(this)
}
}
}
오브젝트.data.함수();
👉 { 함수 : ƒ }
결론 : 나를 담고 있는 오브젝트를 출력함
constructor 안에서 쓰면 constructor로 새로생성되는 오브젝트
constructor는 오브젝트 복사해서 생성해주는 기계
function 기계(){
this.이름 = 'kim';
}
var 오브젝트 = new 기계();
함수 문법을 이용해서 만든 후, 안에 this.어쩌구를 추가
여기서 this는 기계로부터 새로 생성될 오브젝트들을 의미
new 키워드를 이용해 새로운 오브젝트를 꺼냄
👉 { 이름 : 'kim' }
eventlistener 안에서 쓰면 this는 e.currentTarget이라는 의미
document.getElementById('버튼').addEventListener('click', function(e){
console.log(this)
});
여기서 this는 e.currentTarget과 같은 의미
e.currentTarget은 지금 이벤트가 동작하는 곳
즉, 지금 addEventListener 부착된 HTML 요소
◻ 이벤트리스너 안에서 콜백함수
document.getElementById('버튼').addEventListener('click', function(e){
var 어레이 = [1,2,3];
어레이.forEach(function(){
console.log(this)
});
});
👉 window
◻ 오브젝트 안에서 콜백함수
var 오브젝트 = {
이름들 : ['김', '이', '박'];
함수 : function(){
오브젝트.이름들.forEach(function(){
console.log(this)
});
}
}
👉 window
⭐ arrow function
this값은 function을 만날 때마다 바뀔 수 있기 때문에 내가 원하는 this를 쓰기 힘듦.
그럴 땐 함수를 arrow function으로 바꿔보자.
var 오브젝트 = {
이름들 : ['김', '이', '박'];
함수 : function(){
오브젝트.이름들.forEach(() => {
console.log(this)
});
}
}
function () {} 대신 쓸 수 있는 () => {} 이라는 arrow function 문법을 사용하면,
함수 내부의 this값을 새로 바꿔주지 않아 this를 사용할때 유용.
🍎 코딩애플 강의 : 매우쉽게 이해하는 JavaScript 객체지향 & ES6 신문법