Search

this

1. 바인딩 규칙

(1) 기본 바인딩 (Default Binding)

function foo() { console.log(this); } foo();
JavaScript
복사
엄격 모드('use strict' / ESM / TS 기본) → this === undefined
비엄격 모드(슬로피) → this === 전역 객체(window / global)
(2) 암시적 바인딩 (Implicit Binding)
const obj = { x: 10, foo() { console.log(this.x); } }; obj.foo(); // 10
JavaScript
복사
함수가 객체의 프로퍼티로 호출될 경우 → this는 점(.) 왼쪽의 객체.
(3) 명시적 바인딩 (Explicit Binding)
function foo(this: any, y: number) { console.log(this.x + y); } const obj = { x: 10 }; foo.call(obj, 5); // 15 foo.apply(obj, [7]); // 17 const bound = foo.bind(obj); bound(3); // 13
JavaScript
복사
call, apply, bind로 this를 명시적으로 지정.
(4) new 바인딩 (Constructor Call)
function Person(this: any, name: string) { this.name = name; } const p = new (Person as any)('Jun'); console.log(p.name); // "Jun"
JavaScript
복사
new 키워드로 호출 시, 새로운 객체가 생성되고 그 객체가 this.
(5) 화살표 함수 바인딩 (Lexical Binding)
const obj = { x: 42, foo: () => { console.log(this?.x); } }; obj.foo(); // undefined
JavaScript
복사
화살표 함수는 자신만의 this를 가지지 않고, 선언된 **상위 스코프의 this**를 캡처한다.
React 이벤트 핸들러에서 자주 쓰이는 이유 → 클래스에서 this 고정 문제를 회피.
“this는 선언 시점이 아니라 호출 시점에 의해 결정된다. 다만 화살표 함수는 예외적으로 선언된 환경의 this를 캡처한다.”

2. 예시문제

export {}; // 모듈 스코프로 엄격 모드 유지 function whoAmI() { console.log('A:', this); } const obj = { whoAmI, callMe() { console.log('B:', this); }, }; whoAmI(); // (1) obj.whoAmI(); // (2) obj.callMe(); // (3) const f = obj.callMe; f(); // (4)
JavaScript
복사
JavaScript
복사