해당 글은 하단 강의와 교안을 바탕으로 작성되었습니다.
https://www.youtube.com/playlist?list=PLlaP-jSd-nK9LiA2n07uBhzOn9wI53xGV
프론트엔드 날개달기
이 강의를 통해 Webpack, NPM, 모듈시스템 등 프론트엔드 개발자가 되기 전에 꼭 알아야할 지식을 탄탄히 다질 수 있습니다.
www.youtube.com
자바스크립트의 this 키워드 이해하기
this란 무엇인가?
- this는 자바스크립트에서 객체를 가리키는 키워드이다.
- ⇒ 간단히 말해 this는 호출한 객체를 의미한다! 호출한 놈!!
- 호출한 객체가 없으면 기본값은 전역 객체인 window이다.
- 예외도 있다
- 전역스코프에서 this는 window 객체 이다.
- 화살표 함수(Arrow Function)에서 this가 조금 달라진다.
- Strict Mode에서는 this가 조금 달라진다.
this의 정의: 호출한 객체
- this는 호출한 객체를 가리킵니다.
- 예외가 없으면 기본값은 window 객체이다.
- 전역 스코프에서의 this
// 웹 브라우저에서 window 객체가 전역 객체임
console.log(this === window); // true
- 대부분의 경우 this의 값은 함수를 호출한 방법에 의해 결정된다. MDN
기본 예제
- 객체 생성:
const person = {
name: 'Coding',
age: 20,
printThis: function() {
console.log(this);
}
};
person.printThis(); // person 객체를 가리킴
2. 함수 호출 시 this:
const printThis = person.printThis;
printThis(); // window 객체를 가리킴
this의 기본 동작
- 객체의 메서드를 호출하면 this는 해당 객체를 가리킨다.
- 함수 단독 호출 시 this는 전역 객체(window)를 가리킨다.
예제 실습
- 객체 내부 메서드에서 this:
const person = {
name: 'John',
age: 30,
printThis: function() {
console.log(this); // person 객체
}
};
person.printThis();
2. 함수 외부에서 호출 시 this:
const printThis = person.printThis;
printThis(); // window 객체
this와 콜백 함수
- 콜백 함수 내부에서 this는 window 객체를 가리킨다:
setTimeout(function() {
console.log(this); // window 객체
}, 1000);
this 바인딩
- this를 특정 객체로 바인딩하기 위해 bind 메서드를 사용한다:
function printThis() {
console.log(this);
}
const boundPrintThis = printThis.bind(person);
boundPrintThis(); // person 객체
bind 메서드
- bind를 사용하여 함수의 this를 명시적으로 설정한다:
const person = {
name: 'Alice',
printThis: function() {
console.log(this);
}
};
const boundPrintThis = person.printThis.bind(person);
boundPrintThis(); // person 객체
화살표 함수와 this
화살표 함수(Arrow Function)가 나오기 전까지는 함수는 어떻게 호출되는지에 따라 자신의 this 값을 정의했다.
하지만 화살표 함수는 자신을 포함하고 있는 외부 Scope에서 this를 계승받는다!
- 화살표 함수는 자신의 스코프에서 this를 계승받는다:
const person = {
name: 'Alice',
printThis: function() {
setTimeout(() => {
console.log(this); // person 객체
}, 1000);
}
};
person.printThis();
this와 엄격 모드
- 엄격 모드(strict mode)에서는 this가 undefined가 된다:
'use strict';
function printThis() {
console.log(this); // undefined
}
printThis();
주의할 점
- 메서드 정의 시 화살표 함수를 사용하면 this가 전역 객체를 가리킬 수 있다:
const person = {
name: 'Bob',
printThis: () => {
console.log(this); // window 객체
}
};
person.printThis();
+ 화살표 함수를 사용하면 안되는 경우!!
- 객체 메서드를 선언할 때 사용하면 안된다.
let person = {
name: '짐코딩',
printThis: () => {
console.log(this); // window 객체 출력
}
};
2. addEventListener 함수의 콜백 함수에서 사용하면 this가 상위 컨텍스트를 가리킨다.
- 화살표 함수로 등록하면 this → window 객체
let btn = document.querySelector('button');
button.addEventListener('click', () => {
console.log(this === window); // => true
this.innerHTML = 'Clicked button';
});
- 일반 함수로 등록하면 this → button 요소
let btn = document.querySelector('button');
button.addEventListener('click', function() {
console.log(this === button); // => true
this.innerHTML = 'Clicked button';
});
728x90
'자바스크립트' 카테고리의 다른 글
[JS] 한 페이지에서 많은 API 호출을 효율적으로 처리하는 방법 / Promise.all 사용하기 (0) | 2024.07.09 |
---|---|
이벤트 버블링&캡쳐링, 이벤트 전파 (0) | 2024.07.08 |
파일 효과적으로 가져오기 | script defer, async (0) | 2024.07.08 |
BOM 이란? (0) | 2024.07.08 |
DOM 이란? (0) | 2024.07.08 |