this = window (기본)
바뀌는 경우
1. 객체 메서드 안에서 this = 객체
2. this를 바꾸는 함수 셋 : blind, call, apply 사용
3. new로 생성자 함수 호출 시 this = 생성자를 통해 생성된 인스턴스
4. 이벤트 리스너 / jQuery 사용 시 내부적으로 this가 바뀐다.
$('div').on('click', function() {
console.log(this); // <div>
});
하지만 기본적으로 this는 window를 가리키기 때문에 아래와 같은 예시에서 this는 다시 window를 가리키게 됨.
$('div').on('click', function() {
console.log(this); // <div>
function inner() {
console.log('inner', this); // inner Window
}
inner();
});
- 해결 방법 1) 변수에 담아 사용하기
- 해결 방법 2) ES6 화살표 함수 사용하기
$('div').on('click', function() {
console.log(this); // <div>
const inner = () => {
console.log('inner', this); // inner <div>
}
inner();
});
ES6 화살표 함수는 상위 함수의 this를 가져온다.
출처: https://www.zerocho.com/category/JavaScript/post/5b0645cc7e3e36001bf676eb
'자율 학습 > 학습' 카테고리의 다른 글
[Spring MVC, Ajax, JavaScript] 다중 파일 첨부 후 수정할 때 (0) | 2022.09.29 |
---|---|
[JavaScript] return, return true, return false 의미와 사용 (0) | 2022.09.29 |
개수, name, id가 유동적인 태그의 값을 수정하는 페이지 (0) | 2022.09.27 |
[JSTL] forEach의 varStatus를 ID로 사용할 때 (0) | 2022.09.26 |
[SQL] 즐겨찾기, 좋아요 온오프 (아예 없는 데이터 조회하기 - NVL 사용 불가) (0) | 2022.09.23 |