ES6부터 화살표 함수( arrow function)이 도입되었다. function이라는 키워드와 중괄호를 생략할 수 있는 이점이 있다.
const f1 = function() { return 'hello!'; }
// 위 아래 코드는 동등한 결과 출력
const f1 = () => 'hello!';
function을 생략했고 오로지 'hello'만 출력하므로 {}, return 까지 건너뛸 수 있다.
const f2 = function(name) { return `Hello, ${name}!`; }
// 위 아래 코드는 동등한 결과 출력
const f2 = name => `Hello, ${name}! `;
f2는 파라미터로 name 한 개만 가질 수 있다. 따라서 (name)을 'name'처럼 괄호를 생략하고 {}, return을 건너뛴다.
const f3 = function(a, b) { return a + b; }
// 위 아래 코드는 동등한 결과 출력
const f3 = (a, b) => a + b;
파라미터가 a, b 두 개인 경우 ()는 생략할 수 없지만 function, {}, return은 생략 가능하다.
화살표 함수에서 this는 정적으로 바인딩된다. 따로 this가 정의되있지 않다. 따라서 외부의 this를 참조한다.
let group = {
title: "group1",
students: ["david", "lucas", "henderson"],
showList() {
this.students.forEach(
student => alert(this.title + ': ' + student)
);
}
};
group.showList();
화살표 함수의 this는 바깥의 코드블록인 showList()함수의 this.title인 group.title을 가리킨다.
let group = {
title: "group1",
students: ["david", "lucas", "henderson"],
showList() {
this.students.forEach(function(student) {
// TypeError: Cannot read property 'title' of undefined
alert(this.title + ': ' + student)
});
}
};
group.showList();
일반함수로 접근하면 this.title이 undefined 된다.
참고
1) Learning JavaScript(한빛미디어)
2) https://ko.javascript.info/arrow-functions-basics
3) https://ko.javascript.info/arrow-functions