this
this는 실행 컨텍스트에 따라 다른 값을 가짐
this 바인딩은 함수가 호출되는 방식에 의해 결정
기본적인 this의 동작
- 전역 컨텍스트
- 브라우저 환경:
window 객체
- Node.js 환경:
global 객체 또는 undefined (strict mode)
- 함수 내부
- 일반 함수 호출: 전역 객체 (
window 또는 global)
- strict mode (
'use strict' 적용): undefined
function showThis() {
console.log(this);
}
showThis();
객체의 메서드에서 this
- 객체의 메서드 내부에서
this는 해당 객체를 가리킴
const obj = {
name: "JavaScript",
showThis() {
console.log(this);
}
};
obj.showThis();
생성자 함수에서 this
- 생성자 함수 내부에서
this는 새로 생성되는 객체를 가리킴
function Person(name) {
this.name = name;
}
const user = new Person("John");
console.log(user.name);
화살표 함수에서 this
- 화살표 함수는 자신만의
this를 가지지 않고, 상위 스코프의 this를 상속
- 화살표 함수는
bind(), call(), apply()로도 this를 변경할 수 없음
const obj = {
name: "JavaScript",
showThis: () => {
console.log(this);
}
};
obj.showThis();
this의 명시적 바인딩 (call, apply, bind)
call(), apply(), bind()를 사용하면 this를 특정 객체로 지정 가능
function greet() {
console.log(this.name);
}
const user = { name: "Alice" };
greet.call(user);
greet.apply(user);
const boundGreet = greet.bind(user);
boundGreet();
클래스에서의 this
- 클래스의 메서드 내부에서
this는 해당 인스턴스를 가리킴
class Person {
constructor(name) {
this.name = name;
}
showThis() {
console.log(this);
}
}
const user = new Person("Bob");
user.showThis();
- 클래스 메서드를 이벤트 핸들러로 사용하면
this가 바뀔 수 있으므로 bind()가 필요할 수 있음
class Counter {
constructor() {
this.count = 0;
}
increase() {
console.log(this);
this.count++;
}
}
const counter = new Counter();
const button = document.querySelector("button");
button.addEventListener("click", counter.increase.bind(counter));
this와 이벤트 리스너
- 일반 함수로 이벤트 리스너를 등록하면
this는 이벤트를 발생시킨 DOM 요소를 가리킴
- 화살표 함수로 이벤트 리스너를 등록하면
this는 상위 스코프의 this를 따름
const button = document.querySelector("button");
button.addEventListener("click", function () {
console.log(this);
});
button.addEventListener("click", () => {
console.log(this);
});
| 호출 방식 | this가 가리키는 대상 |
|---|
| 전역 컨텍스트 | 브라우저: window / Node.js: global (strict mode에서는 undefined) |
| 일반 함수 호출 | window 또는 global (strict mode에서는 undefined) |
| 객체의 메서드 호출 | 해당 객체 |
생성자 함수 호출 (new 사용) | 새로 생성된 객체 |
| 화살표 함수 | 상위 스코프의 this를 상속 |