화살표 함수
ES6에서 도입된 함수 표현식의 간결한 문법입니다. function 키워드 대신 =>를 사용하며, this 바인딩이 다릅니다.
기본 문법
// 기존 함수 표현식
const add = function(a, b) {
return a + b;
};
// 화살표 함수
const add = (a, b) => {
return a + b;
};
// 더 간결하게 (한 줄이면 return 생략)
const add = (a, b) => a + b;
문법 변형
// 매개변수 없음
const sayHello = () => "Hello";
// 매개변수 1개 (괄호 생략 가능)
const double = x => x * 2;
// 매개변수 여러 개
const add = (a, b) => a + b;
// 여러 줄
const calculate = (a, b) => {
const sum = a + b;
const product = a * b;
return { sum, product };
};
// 객체 반환 (괄호로 감싸야 함)
const createUser = (name, age) => ({ name, age });
일반 함수 vs 화살표 함수
| 항목 | 일반 함수 | 화살표 함수 |
|---|---|---|
| this | 호출 방식에 따라 결정 | 상위 스코프의 this |
| arguments | 사용 가능 | 사용 불가 |
| 생성자 | 가능 (new) | 불가능 |
| 메서드 | 적합 | 부적합 |
this 바인딩 차이
// 일반 함수 - this가 호출 시점에 결정
const obj = {
name: "홍길동",
greet: function() {
setTimeout(function() {
console.log(this.name); // undefined (this가 window)
}, 100);
}
};
// 화살표 함수 - 상위 스코프의 this 사용
const obj = {
name: "홍길동",
greet: function() {
setTimeout(() => {
console.log(this.name); // "홍길동" (this가 obj)
}, 100);
}
};
화살표 함수 사용하면 안 되는 경우
객체 메서드
// X this가 상위 스코프 (window)
const user = {
name: "홍길동",
greet: () => {
console.log(this.name); // undefined
}
};
// O 일반 함수 사용
const user = {
name: "홍길동",
greet() {
console.log(this.name); // "홍길동"
}
};
생성자 함수
// X 생성자로 사용 불가
const Person = (name) => {
this.name = name;
};
new Person("홍길동"); // TypeError
// O 일반 함수 사용
function Person(name) {
this.name = name;
}
new Person("홍길동"); // OK
이벤트 핸들러 (this 필요 시)
// X this가 버튼이 아님
button.addEventListener('click', () => {
console.log(this); // window
});
// O 일반 함수 사용
button.addEventListener('click', function() {
console.log(this); // button 요소
});
화살표 함수가 적합한 경우
// 콜백 함수
[1, 2, 3].map(x => x * 2);
[1, 2, 3].filter(x => x > 1);
// Promise, async/await
fetch(url)
.then(res => res.json())
.then(data => console.log(data));
// 상위 스코프 this 유지
class Component {
constructor() {
this.value = 10;
}
handleClick = () => {
console.log(this.value); // 항상 10
};
}
정리
화살표 함수 사용 O
- 콜백 함수
- 배열 메서드
- this 유지 필요
일반 함수 사용 O
- 객체 메서드
- 생성자 함수
- this 동적 바인딩 필요