2026-03-03
this의 용법
this란 무엇인가
- 함수를 호출할때 생성되는 실행 컨텍스트 객체
- 실행 컨텍스트에 따라 동적으로 결정되는 키워드
- this는 함수가 호출되는 방식에 따라 결정되는 값
- 함수를 호출할 때, 함수 내에서 현재 객체를 참조하는 데 사용
this
- 전역 호출 (Global Binding)
- 일반 함수로 호출된 경우 this는 전역 전체임임
function test() { console.log(this); } test();- 브라우저 → window
- Node.js환경 → global 객체
- strict mode → undefined
- 객체 메서드 호출 (Implicit Binding)
- 메소드로 호출된 경우 this는 해당 메서드가 속한 객체체
const obj = { name: "JS", show() { console.log(this.name); } }; obj.show();⇒ this = obj
- 명시적 바인딩 (Explicit Binding)
- this 바인딩
- 바인딩이란 식별자와 값을 연결하는 것
- this 바인딩은 this와 this가 가리킬 객체를 연결하는것
- this 바인딩은 함수 호출 방식에 따라 동적으로 결정
- 함수가 호출될 때 apply, call 또는 bind가 사용되었다면
- 첫번째 인자로 전달하는 값에 this 를 바인딩
function show() { console.log(this.name); } show.call({ name: "React" });- call
- apply
- bind
⇒ 직접 this를 지정
- this 바인딩
- 생성자 호출 (new Binding)
- 생성자 함수 내부에서의 this 는 생성자 함수가 생성할 인스턴스가 바인딩
function Person(name) { this.name = name; } const p = new Person("JS");⇒ this = 새로 생성된 객체
화살표 함수의 this
화살표 함수는 자신의 this를 가지지 않는다.
- 화살표 함수에는 this 존재 X
- 화살표 함수에서 this 를 사용하면, 외부 스코프의 this 를 그대로 사용
const obj = {
name: "JS",
arrow: () => console.log(this.name)
};
⇒ 상위 스코프의 this를 그대로 사용 (Lexical this)
프론트엔드에서 자주 나오는 상황
-
이벤트 핸들러에서 this
button.addEventListener("click", function () { console.log(this); });⇒ this = 클릭된 DOM 요소
-
React 클래스 컴포넌트
class App extends React.Component { handleClick() { console.log(this); } }⇒ this 바인딩 필요
this.handleClick = this.handleClick.bind(this);또는 화살표 함수 사용
요약
this는 함수가 호출되는 방식에 따라 결정됩니다. 전역 호출, 객체 메서드 호출, 명시적 바인딩, 생성자 호출에 따라 달라지며, 화살표 함수는 자체적인 this를 가지지 않고 상위 스코프의 this를 사용합니다.
참고자료
- https://inpa.tistory.com/entry/JS-%F0%9F%93%9A-this-%EC%B4%9D%EC%A0%95%EB%A6%AC
- https://velog.io/@o1011/JavaScript-this-%EB%9E%80
- https://yooneeee.tistory.com/123
- https://velog.io/@hjng0825/this-%EB%9E%80
- https://nykim.work/71