이것은 this
JavaScript에서 this 키워드는 호출 문맥(context)에 따라 달라지는 매우 중요한 개념이다.
어렵단 말이다.
1. this란?
this는 현재 실행 중인 코드의 문맥(실행 환경)을 참조하는 키워드이다.
쉽게 말하면 this를 '누가 호출했느냐?'에 따라 참조하는 객체가 달라진다.
1) this의 동작 방식
- 전역 문맥 (Global Context)
console.log(this); // 브라우저: window / Node.js: global
브라우저 환경에서는 this === window,
Node.js에서는 this === global.
- 일반 함수 호출
function sayHi() {
console.log(this);
}
sayHi(); // 브라우저: window / 엄격 모드(strict mode): undefined
기본 모드에서는 this가 전역 객체(window)를 참조.
'use strict' 모드에서는 undefined로 설정됨.
- 메서드 호출
const user = {
name: "Jin",
greet() {
console.log(this.name);
},
};
user.greet(); // Jin
객체의 메서드로 호출하면, this는 그 메서드를 소유한 객체를 참조
- 생성자 함수
function Person(name) {
this.name = name;
}
const p = new Person("Jin");
console.log(p.name); // Jin
new 키워드로 호출하면, this는 새로 생성된 인스턴스 객체를 참조
- 화살표 함수
const obj = {
name: "Arrow",
greet: () => {
console.log(this.name);
},
};
obj.greet(); // undefined
화살표 함수는 this를 가지지 않으며, 외부 스코프의 this를 그대로 사용함
- 명시적 바인딩: call, apply, bind
function sayHello() {
console.log(this.name);
}
const user = { name: "Jin" };
sayHello.call(user); // Jin
sayHello.apply(user); // Jin
const boundFn = sayHello.bind(user);
boundFn(); // Jin
call, apply, bind를 사용하면 this를 명시적으로 지정할 수 있음
2. 결론
호출 방식 | this가 참조하는 것 |
전역에서 | window (또는 global) |
일반 함수 | window (또는 undefined in strict mode) |
메서드 | 메서드를 호출한 객체 |
생성자 함수 | 새로 생성된 객체 |
화살표 함수 | 외부 스코프의 this |
call / apply / bind | 지정한 객체 |
JavaScript에서 this는 '함수가 어떻게 호출되었는지'를 기준으로 이해해야 한다.
이벤트 핸들러, 클래스 내 메서드 등을 사용할 때는 this의 동작 방식을 정확히 이해하고 있어야 오류를 줄일 수 있다.
- 나중에 내용 추가 수정할 예정...
'코딩 > 기초' 카테고리의 다른 글
[JavaScript] 렉시컬 스코프란? (1) | 2025.05.01 |
---|---|
[JavaScript] var, let, const가 뭔데? : 변수 (2) | 2025.04.28 |
브라우저란? : Browser 동작 원리 (2) | 2025.04.25 |
시맨틱 태그란? : 이것은 원고지다 (0) | 2025.04.24 |
[CSS] Cascading이란? : 적용 순서 (0) | 2025.04.24 |