ES6 - 화살표 함수

marafo·2020년 9월 19일
1
post-thumbnail

✳︎ 개요

ES6부터 화살표 함수( arrow function)이 도입되었다. function이라는 키워드와 중괄호를 생략할 수 있는 이점이 있다.

✔︎ function 키워드 생략 가능

✔︎ 함수의 파라미터가 하나일 때 ()괄호도 생략 가능

✔︎ 함수 바디가 하나의 표현식만 갖는다면 중괄호, return 생략 가능

✔︎ 항상 익명함수

✔︎ new 생성자와 함께 쓸 쑤 없다. this가 없기 때문이다.

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가 정의되있지 않다. 따라서 외부의 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

profile
프론트 개발자 준비

0개의 댓글