화살표 함수

ES2015 이후 화살표 함수가 나오게 되었다.

function add1(x, y) {
  return x + y;
}
 
function not1(x) {
  return !x;
}

ES2015 이전에 함수는 위처럼 사용했어야 했으나, ES2015 이후 다음처럼 표현이 가능해졌다.

const add2 = (x, y) => {
  return x + y;
}
 
const add3 = (x, y) => x + y;
 
const add4 = (x, y) => (x + y);
 
const not2 = x => !x;

화살표 함수로 객체 return 하는 방법

다음과 같은 함수를 화살표 함수가 있다

const obj = (x, y) => {
  return { x: x, y: y };
}

객체 리터럴에 의해 아래처럼 x와 y가 생략이 가능하다.

const obj = (x, y) => {
  return { x, y };
}

또한 바로 return이 되기 때문에 return 생략이 가능하다.

const obj = (x, y) => { x, y };

근데 여기서 문제가 발생한다. { x, y }에 있는 { }를 자바스크립트는 바디의 태그를 의미하는지 객체의 리터럴을 의미하는지 인식을 못한다.

따라서 객체를 리턴하는 경우에는 소괄호가 필수다.

const obj = (x, y) => ({ x, y });

function vs 화살표 함수

화살표 함수가 기존 function()을 대체하는 건 아니다.

function에서는 this를 따로 갖는 반면, 화살표 함수는 부모의 this를 물려받는다.

아래와 같은 예시를 통해 알 수 있다.

var relationship1 = {
  name: 'zero',
  friends: ['nero', 'hero', 'xero'],
  logFriends: function() {
    this.friends.forEach(function (friend) {
      console.log(this.name, friend);
    });
  },
};
relationship1.logFriends();

this는 function 안에 종속된다. logFriends 메서드의 this값을 보면, forEach의 function의 this와 logFriends의 this는 다르다.

따라서 아래와 같은 결과값이 나온다.

// 결과값
undefined nero
undefined hero
undefined xero

그렇기 때문에 기존에는 아래와 같이 that이라는 중간 변수를 이용해서 logFriends의 this를 전달하여 부모의 this를 받았어야 했다.

var relationship1 = {
  name: 'zero',
  friends: ['nero', 'hero', 'xero'],
  logFriends: function() {
    var that = this; // relationship1을 가리키는 this를 that에 저장
    this.friends.forEach(function (friend) {
      console.log(that.name, friend);
    });
  },
};
relationship1.logFriends();
// 결과값
zero nero
zero hero
zero xero

반면, 화살표 함수는 부모의 this를 물려받기 때문에 다음과 같이 사용할 수 있다.

var relationship1 = {
  name: 'zero',
  friends: ['nero', 'hero', 'xero'],
  logFriends: function() {
    this.friends.forEach( friend => {
        console.log(this.name, friend)
    })
  },
};
relationship1.logFriends();

forEach의 화살표 함수의 this와 logFriends의 this가 같아진다.

화살표 함수는 자신을 포함하는 함수의 this를 물려받는다. 그렇기 때문에 부모의 this를 물려받고 싶지 않을 때는 일반함수(:function() {})를 사용하면 된다.