화살표 함수와 this
일반 함수의 this가 호출 방식에 따라 정해지고 화살표 함수는 바깥의 this를 그대로 쓴다는 차이를 예제로 추적하고, this 매개변수와 bind, 화살표 함수 속성으로 콜백에 넘길 메서드를 고친 뒤, 3장의 주문 프로그램을 완성합니다.
주문을 하나씩 담는 장바구니 객체를 만들고, 그 객체의 메서드를 배열의 forEach나 타이머에 콜백으로 넘기는 일은 흔합니다. 그런데 객체에서 꺼내 넘긴 메서드는 자기가 어느 객체의 것이었는지 기억하지 못합니다. 자바스크립트의 this는 함수를 어디에 선언했는지가 아니라 어떻게 호출했는지에 따라 정해지기 때문입니다.
이 글을 읽고 나면 다음을 할 수 있습니다.
- 일반 함수와 화살표 함수에서
this가 무엇이 되는지를 호출 방식에서 추적합니다. this매개변수로 잘못된 호출을 진단받고,bind와 화살표 함수 속성으로 콜백에 넘길 메서드를 고칩니다.- 3장에서 키운
order.ts를 주문을 담아 영수증을 출력하는 프로그램으로 완성합니다.
이 글의 예제는 클래스를 씁니다. class 안에 속성과 메서드를 적고 new로 객체를 만든다는 것만 알면 따라올 수 있고, 자세한 문법은 4장의 클래스 기본 문법에서 다룹니다. ts-first 폴더에 this-binding.ts를 만들고 include를 ["this-binding.ts"]로 바꾼 뒤, 코드를 덧붙일 때마다 tsc -p .과 node dist/this-binding.js를 실행합니다.
일반 함수의 this는 호출 방식이 정한다
인사말을 속성으로 가진 클래스를 만들고, 메서드에서 this로 그 속성을 읽습니다.
class TraditionalGreeter {
greeting = "Hello";
sayGreeting(name: string) {
console.log(`${this.greeting}, ${name}!`);
}
}
const tg = new TraditionalGreeter();
tg.sayGreeting("TypeScript");Hello, TypeScript!이번에는 메서드를 변수에 따로 담아 부릅니다. 다음 두 줄을 잠시 추가하면 검사와 실행은 각각 어떻게 될까요? 먼저 예상해 보세요.
const detached = tg.sayGreeting;
detached("TypeScript");결과 확인하기
tsc -p .은 진단 없이 끝나지만, 실행하면 첫 줄을 출력한 뒤 TypeError: Cannot read properties of undefined (reading 'greeting')로 멈춥니다. tg.sayGreeting(...)은 tg를 통해 불렀으므로 this가 tg였습니다. detached(...)는 아무 객체도 거치지 않았고, 클래스의 코드는 항상 엄격 모드여서 this가 undefined가 됩니다.
function 키워드로 만든 함수와 클래스의 메서드에서 this는 호출하는 순간에 정해집니다. obj.method()처럼 객체를 통해 부르면 그 객체가, call이나 apply, bind로 부르면 직접 넘긴 값이 this가 됩니다. 두 줄을 지우고 다음으로 넘어갑니다.
메서드 안에서 타이머에 일반 함수를 콜백으로 넘길 때도 같은 일이 생깁니다. TraditionalGreeter의 sayGreeting 아래에 다음 메서드를 잠시 추가합니다.
sayGreetingLater() {
setTimeout(function () {
console.log(`${this.greeting}, world!`);
}, 100);
}error TS2683: 'this' implicitly has type 'any' because it does not have a type annotation.콜백을 부르는 것은 tg가 아니라 타이머이므로, 그 안의 this는 메서드가 받은 this와 관계가 없습니다. strict에 포함된 noImplicitThis 설정이 이렇게 타입을 알 수 없는 this를 TS2683으로 알려 줍니다. 이 메서드도 지웁니다.
화살표 함수는 바깥의 this를 쓴다
함수 타입 정의의 multiply처럼 =>로 만드는 화살표 함수(arrow function)에는 자기만의 this가 없습니다. 함수 안에서 this를 쓰면, 화살표 함수를 만든 곳을 감싸는 바깥 코드의 this를 그대로 가리킵니다. 이것을 렉시컬 this(lexical this)라고 합니다.
class ArrowGreeter {
greeting = "Hello";
sayGreetingLater() {
setTimeout(() => {
console.log(`${this.greeting}, world!`);
}, 100);
}
}
const ag = new ArrowGreeter();
ag.sayGreetingLater();Hello, world!화살표 함수는 sayGreetingLater 안에서 만들어졌으므로, 그 메서드가 호출될 때 받은 this, 곧 ag를 씁니다. 타이머는 약 0.1초 뒤에 실행되므로, 이 줄은 뒤에 덧붙일 코드의 출력이 모두 끝난 다음 맨 마지막에 나옵니다.
TYPE / RUNTIME / CONTRACT
일반 함수는 호출 방식, 화살표 함수는 바깥 this
본문의 일반 타이머 콜백은 Greeter 인스턴스를 캡처하지 않습니다. 메서드 안의 실제 화살표 함수는 메서드가 받은 this를 유지합니다.
REGULAR FUNCTION
obj.method()의 receiver는 obj
메서드를 값으로 꺼내 전달하면 꺼낸 객체가 this로 자동 유지되지 않습니다. 타이머 receiver는 호스트마다 달라 TraditionalGreeter의 지연 호출 결과를 하나로 단정할 수 없습니다.
ACTUAL ARROW
메서드 안에서 바깥 this를 캡처
ArrowGreeter의 setTimeout(() => …)는 인스턴스 greeting을 사용해 Hello, world!을 출력합니다. call·bind로 화살표 함수의 this를 바꿀 수 없습니다.
BIND / IDENTITY
함수 참조를 한 번 만들어 보관
handler.handleClick.bind(handler)는 handler를 receiver로 고정합니다. 이벤트 제거 등에 같은 참조가 필요하면 만들어 둔 bound 함수를 보관합니다. 이 참조 관리 설명은 설계 확장입니다.
STATIC THIS
타입 표기가 자동 바인딩은 아닙니다
this: ButtonHandler는 JavaScript 매개변수에서 제거됩니다. 함수 타입 (message: string) => void도 실제 구현을 화살표 함수로 바꾸지 않습니다. MyLogger는 생성자에서 실제 화살표 함수를 할당합니다.
화살표 함수도 자신을 감싼 메서드가 잘못된 receiver로 호출되면 그 this를 캡처합니다. 필요한 receiver와 실제 호출 방식을 함께 확인합니다.
위 그림처럼 this를 판단할 때는 먼저 그 함수가 실제로 화살표 함수인지를 봅니다. 화살표 함수라면 바깥의 this를, 일반 함수라면 호출할 때의 대상을 씁니다. 아래 카드의 bind와 this의 타입 표기는 이어지는 두 절에서 다룹니다.
this 매개변수로 잘못된 호출 진단받기
앞의 detached 호출은 검사를 통과했습니다. 타입스크립트에서는 함수의 첫 매개변수 자리에 this라는 이름으로 this의 타입을 적어, 이런 호출을 진단받을 수 있습니다. 이 this 매개변수는 실제 인수가 아니어서 호출할 때 넘기지 않고, 컴파일한 자바스크립트에서도 지워집니다.
class ButtonHandler {
buttonLabel = "저장";
handleClick(this: ButtonHandler, event: Event) {
console.log(`버튼 '${this.buttonLabel}'이 클릭되었습니다. (${event.type})`);
}
}
const handler = new ButtonHandler();
handler.handleClick(new Event("click"));
const boundHandleClick = handler.handleClick.bind(handler);
boundHandleClick(new Event("click"));버튼 '저장'이 클릭되었습니다. (click)
버튼 '저장'이 클릭되었습니다. (click)const click = handler.handleClick; click(new Event("click"));처럼 따로 담아 부르면, 이번에는 The 'this' context of type 'void' is not assignable to method's 'this' of type 'ButtonHandler'.라는 TS2684가 나옵니다. bind(handler)는 this를 handler로 고정한 새 함수를 만들므로, boundHandleClick은 그냥 불러도 됩니다. Event는 브라우저의 타입이지만 Node.js 24에도 전역 Event가 있어 그대로 실행됩니다.
콜백으로 넘길 메서드는 화살표 함수 속성으로
메서드를 콜백으로 자주 넘긴다면, 넘길 때마다 bind하는 대신 클래스의 속성에 화살표 함수를 넣는 방법이 있습니다. 화살표 함수는 인스턴스를 만들 때 생성자 안에서 만들어지므로, 그 인스턴스를 this로 계속 씁니다.
interface Logger {
logLevel: string;
logMessage: (message: string) => void;
}
class MyLogger implements Logger {
logLevel = "INFO";
logMessage: (message: string) => void;
constructor() {
this.logMessage = (message: string) => {
console.log(`[${this.logLevel}] ${message}`);
};
}
}
const logger = new MyLogger();
const log = logger.logMessage;
log("주문 데이터 로드 완료.");[INFO] 주문 데이터 로드 완료.따로 담아 부른 log도 인스턴스를 this로 씁니다. implements Logger는 이 클래스가 인터페이스의 모양을 갖추었는지 검사하게 하는 표시이며, 4장의 상속과 구현에서 다룹니다. 인터페이스의 (message: string) => void는 함수의 타입일 뿐 구현을 화살표 함수로 만들어 주지 않으므로, this를 지키는 것은 생성자에서 실제로 넣은 화살표 함수입니다.
이 방법에도 대가가 있습니다. 화살표 함수 속성은 프로토타입에 한 번 정의되는 메서드와 달리 인스턴스마다 새 함수가 만들어지고, 자식 클래스에서 super.logMessage()처럼 부모의 구현을 부를 수도 없습니다. 이 차이는 공식 Handbook의 클래스와 this에 정리되어 있습니다.
세 가지 방식을 한 클래스에서 비교하기
read는 this 매개변수를 적은 일반 메서드이고, readArrow는 화살표 함수 속성이며, boundRead는 read를 counter에 bind한 함수입니다. call은 첫 인수를 this로 삼아 함수를 부릅니다. 네 줄의 출력을 먼저 예상해 보세요.
class Counter {
value = 10;
read(this: { value: number }): number {
return this.value;
}
readArrow = (): number => this.value;
}
const counter = new Counter();
const read = counter.read;
const readArrow = counter.readArrow;
const boundRead = counter.read.bind(counter);
console.log(counter.read());
console.log(read.call({ value: 20 }));
console.log(readArrow.call({ value: 20 }));
console.log(boundRead.call({ value: 20 }));결과 확인하기
10
20
10
10일반 메서드 read는 부를 때의 대상을 읽으므로, counter.read()는 10을, call로 다른 객체를 넘긴 호출은 20을 돌려줍니다. 화살표 함수 readArrow와 bind한 boundRead는 call로 넘긴 객체를 무시하고 counter를 읽어 10을 돌려줍니다.
| 코드 | 결과 |
|---|---|
타이머 콜백으로 넘긴 일반 함수 안의 this | 막는다. TS2683, this의 타입을 알 수 없다 |
this 매개변수를 적은 read를 read()로 호출 | 막는다. TS2684, this가 될 값이 없다 |
this 매개변수가 없는 tg.sayGreeting을 떼어 호출 | 못 막는다. 검사를 통과하고 실행 중에 TypeError로 멈춘다 |
더 깊이: 화살표 함수가 갖지 않는 것과 this 표기의 한계
MDN의 화살표 함수 설명에 따르면 화살표 함수는 자기만의 arguments와 super도 갖지 않고, new로 부를 수 없으며, 제너레이터 함수로 만들 수도 없습니다. 그래서 객체의 메서드처럼 호출한 대상을 this로 읽어야 하는 자리에는 일반 함수나 메서드 문법을 씁니다.
this 매개변수는 검사를 위한 표시일 뿐 함수를 bind해 주지 않습니다. 브라우저의 addEventListener는 핸들러를 부를 때 리스너를 등록한 요소를 this로 넘기는데, button.addEventListener("click", handler.handleClick)처럼 메서드를 그대로 등록해도 this에 관한 진단은 나오지 않습니다. 리스너를 this를 적지 않은 EventListener로 받는 오버로드가 있어 호출이 그쪽으로 통과하기 때문입니다. 그런 곳에는 bind한 함수나 화살표 함수를 넘깁니다.
정리
- 일반 함수와 메서드의
this는 호출하는 방식이 정하며, 객체를 거치지 않고 부르면 엄격 모드에서undefined가 됩니다. - 화살표 함수는 자기만의
this가 없어, 만들어진 곳을 감싸는 바깥의this를 그대로 씁니다. strict의noImplicitThis는 타입을 알 수 없는this를 TS2683으로 알려 줍니다.this매개변수는this의 타입을 적어 잘못된 호출을 TS2684로 잡지만, 함수를 자동으로bind하지는 않습니다.- 콜백으로 넘길 메서드는
bind하거나 화살표 함수 속성으로 만들며, 화살표 함수 속성은 인스턴스마다 함수가 생기고super로 부를 수 없습니다.
연습 문제
1. 값을 바꾼 뒤의 세 호출
counter.value를 30으로 바꾼 뒤 read.call({ value: 7 }), readArrow(), boundRead()는 각각 무엇을 돌려주나요?
해설 보기
차례로 7, 30, 30입니다. 일반 함수 read는 call로 넘긴 객체의 value를 읽습니다. readArrow와 boundRead는 같은 counter 인스턴스를 가리키므로 그 객체의 지금 값인 30을 읽습니다. 화살표 함수나 bind가 처음의 숫자 10을 복사해 둔 것이 아닙니다.
2. 화살표 함수의 this 매개변수
const show = (this: Counter) => this.value;는 An arrow function cannot have a 'this' parameter.라는 TS2730으로 진단됩니다. this의 타입을 적은 채로 show.call(counter)가 10을 돌려주도록 고쳐 보세요.
해설 보기
화살표 함수는 바깥의 this를 그대로 쓰므로, 호출할 때 this가 될 값을 받을 자리가 처음부터 없습니다. this의 타입을 적으려면 일반 함수로 만듭니다.
function show(this: Counter): number {
return this.value;
}
console.log(show.call(counter));counter.value를 바꾸지 않았다면 실행 결과에 10이 더해집니다. show()처럼 대상 없이 부르면 TS2684로 진단됩니다.
3. 장 마무리: 주문을 담는 Cart
3장의 종합 과제입니다. 앞 글의 연습 문제까지 진행한 order.ts에서 시작하며, include를 ["order.ts"]로 바꿉니다. 파일의 끝에 다음 코드를 덧붙입니다.
class Cart {
lines: OrderLine[] = [];
customer: string;
constructor(customer: string) {
this.customer = customer;
}
add(line: OrderLine): void {
this.lines.push(line);
}
receipt(options: ReceiptOptions = {}): string {
return formatReceipt(this.lines, this.customer, options);
}
}
const cart = new Cart("민지");
const picked = [gimbap, ramen];
picked.forEach(cart.add);
console.log(cart.receipt({ takeout: true }));- 먼저 그대로 실행해, 검사는 통과하는데 실행이 어디에서 멈추는지 확인합니다.
picked.forEach(cart.add);줄은 그대로 두고Cart만 고쳐, 마지막 줄에민지 / 포장 / 11500원이 출력되게 합니다.
해설 보기
tsc -p .은 진단 없이 끝나지만, node dist/order.js는 앞 글까지의 아홉 줄을 출력한 뒤 TypeError: Cannot read properties of undefined (reading 'lines')로 멈춥니다. forEach는 넘겨받은 함수를 객체 없이 부르므로, add 안의 this가 undefined가 됩니다. add를 화살표 함수 속성으로 바꾸면 this가 언제나 그 Cart 인스턴스입니다.
add = (line: OrderLine): void => {
this.lines.push(line);
};다시 실행해 열 번째 줄에 민지 / 포장 / 11500원이 나오면 완성입니다. Cart를 고치지 않고 picked.forEach((line) => cart.add(line));처럼 화살표 함수로 감싸거나 cart.add.bind(cart)를 넘겨도 됩니다.
| 증상 | 먼저 볼 곳 |
|---|---|
OrderLine이나 formatReceipt를 찾을 수 없다는 진단 | 앞 글들의 연습 문제 코드가 order.ts에 있는지 |
여전히 TypeError로 멈춘다 | add가 add = (...) => { ... }; 모양의 속성인지, tsc -p .을 다시 실행했는지 |
| 합계가 11500이 아니다 | gimbap과 ramen의 단가와 수량 |
완성 파일 전체 보기
앞 글들에서 확인용으로 넣은 출력 줄은 걷어 내고, 마지막에 네 줄만 출력하게 정리한 파일입니다.
type OrderLine = {
name: string;
unitPrice: number;
quantity: number;
};
type PricePolicy = (unitPrice: number, quantity: number) => number;
const subtotal: PricePolicy = (unitPrice, quantity) => {
if (!Number.isInteger(quantity) || quantity < 0) {
throw new RangeError("수량은 0 이상의 정수여야 합니다.");
}
return unitPrice * quantity;
};
function orderTotal(...lines: OrderLine[]): number {
let total = 0;
for (const line of lines) {
total += subtotal(line.unitPrice, line.quantity);
}
return total;
}
type ReceiptOptions = {
takeout?: boolean;
memo?: string;
};
function formatReceipt(
lines: OrderLine[],
customer: string = "손님",
options: ReceiptOptions = {},
): string {
const place = options.takeout ? "포장" : "매장";
let text = `${customer} / ${place} / ${orderTotal(...lines)}원`;
if (options.memo !== undefined) {
text += ` / 메모: ${options.memo}`;
}
return text;
}
function findLine(lines: OrderLine[], name: string): OrderLine | undefined;
function findLine(lines: OrderLine[], minPrice: number): OrderLine[];
function findLine(
lines: OrderLine[],
key: string | number,
): OrderLine | OrderLine[] | undefined {
if (typeof key === "string") {
return lines.find((line) => line.name === key);
}
const minPrice = key;
return lines.filter((line) => line.unitPrice >= minPrice);
}
function last<T>(values: readonly T[]): T | undefined {
return values[values.length - 1];
}
function pluck<T, K extends keyof T>(items: readonly T[], key: K): T[K][] {
return items.map((item) => item[key]);
}
class Cart {
lines: OrderLine[] = [];
customer: string;
constructor(customer: string) {
this.customer = customer;
}
add = (line: OrderLine): void => {
this.lines.push(line);
};
receipt(options: ReceiptOptions = {}): string {
return formatReceipt(this.lines, this.customer, options);
}
}
const gimbap: OrderLine = { name: "김밥", unitPrice: 3500, quantity: 2 };
const ramen: OrderLine = { name: "라면", unitPrice: 4500, quantity: 1 };
const cart = new Cart("민지");
const picked = [gimbap, ramen];
picked.forEach(cart.add);
console.log(cart.receipt({ takeout: true }));
console.log(pluck(cart.lines, "name"));
console.log(findLine(cart.lines, 4000).length);
console.log(last(pluck(cart.lines, "unitPrice")));민지 / 포장 / 11500원
[ '김밥', '라면' ]
1
4500더 해 보고 싶다면 다음 두 가지를 직접 붙여 보세요. 하나는 Cart에 품목 이름을 받아 그 줄을 빼는 remove를 더하고, picked 대신 이름의 배열에 forEach로 넘겨도 동작하게 하는 것입니다. 다른 하나는 receipt의 옵션에 할인율 rate를 더해, 선택적 매개변수와 기본 매개변수의 applyDiscount처럼 0을 넘겼을 때와 생략했을 때가 구별되게 하는 것입니다.
이것으로 3장의 함수와 타입을 마칩니다. 다음 장의 클래스 기본 문법에서는 이 글에서 쓴 클래스의 속성과 생성자, 메서드를 타입과 함께 처음부터 정리합니다.