자바스크립트에서의 this는 객체를 가리키는 키워드며, 어떻게(누가) 호출하는지에 따라 결정됩니다.
자세히 말하면, this는 호출한 주체입니다.
*아래 예제들은 ‘use strict’를 사용하지 않을 경우를 다룹니다.
호출 주체에 따른 this
호출주체: 전역스코프
console.log(this); // {...window}
function printThis() {
console.log(this);
}
// printThis를 호출한 것은 Window이므로 Window 객체를 출력합니다.
printThis(); // {...window}
호출주체: Object
function printThis() {
console.log(this);
}
const object = {
printThis1: printThis,
functions: {
printThis2: printThis,
}
}
// printThis1을 호출한 것은 'object'이므로 object 객체가 this 입니다.
object.printThis1(); // {printThis1: f, functions: {...}}
// printThis2를 호출한 것은 'functions'이므로 functions 객체가 this 입니다.
object.functions.printThis2(); // {printThis2: f}
호출주체: Event Listener
let btn = document.querySelector('button');
btn.addEventListener('click', function() {
// 이벤트리스너의 'button'이 호출했으므로 this는 button입니다.
console.log(this); // <button>...</button>(=== e.currentTarget)
const arr = [1, 2, 3];
arr.forEach(function(a){
// 콜백함수는 이벤트리스너에서 호출하는 것이 아니므로 window를 가리킵니다.
console.log(this); // {...window}
}
arr.forEach(() => {
// arrow function은 this값을 window로 재설정 하지 않고 그대로 상위 this값을 사용합니다.
console.log(this); // <button>...</button>(=== e.currentTarget)
})
})
호출주체: 생성자
function human() {
// this로 인스턴스를 생성합니다.
this.arm = 2;
this.leg = 2;
}
// new 사용 시 this를 리턴합니다.
const me = new human();
console.log(me); // human {arm: 2, leg: 2, constructor: Object}
호출주체 지정하기(call, bind)
function printThis() {
console.log(this);
}
const object = {
data: 'Kim',
functions: {
printThis: printThis,
}
}
const printer = object.functions.printThis;
// printer를 호출한 것은 'window'이므로 window 객체가 this 입니다.
printer(); // {...window}
const bindedPrint = printer.bind(object);
// bindedPrint를 호출한 것은 'window'지만, object를 this로 고정했으므로 this는 object입니다.
bindedPrinter(); // {data: 'Kim', functions: {...}}
// bind와 달리 즉시 호출한다.
printer.call(object) // {data: 'Kim', functions: {...}}
[참고자료]
this 키워드를 알아보자 1. 함수와 Object에서 사용하면?
'Javascript' 카테고리의 다른 글
| 모듈 (0) | 2024.04.11 |
|---|---|
| 일급객체와 함수 (0) | 2024.04.11 |
| 스코프와 클로저 (0) | 2024.04.11 |
| 실행 컨텍스트: 호이스팅과 스코프 체이닝 (0) | 2024.04.11 |
| 자바스크립트 엔진(Call Stack, Event Loop, …) (0) | 2024.04.11 |