JS & TS

[JS] 화살표 함수

퉁그리 2022. 6. 28. 16:05

이제 function을 굳이 명시 하지 않더라도 화살표 함수를 통해 대체할 수 있게 되었다.

 

function a(x, y) {
  return x + y;
}

var b = (x, y) => {
  return x + y;
}

var c = (x, y) => x + y;

var d = (x, y) => (x + y);

function a2(x) {
  return !x;
}

var b2 = x => !x;

함수 a는 이제 b, c, d의 방식으로 표시할 수 있고, a2도 b2처럼 표할 수 있다.

 

함수 내용이 return 뿐인 경우 c처럼 생략할 수 있으며, 매개변수가 하나인 경우 b2처럼 괄호 생략이 가능하다.

 

return이 생략이 되더라도 가시성을 위해 d처럼 괄호로 감싸는 것을 추천한다.

 

 

화살표함수와 function()은 this에서 차이가 있는데

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

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

화살표 함수는 relationship2에서 보이듯 화살표 함수의 부모 함수의 this을 물려받는 반면

function()은 본인만의 this을 갖는다. 때문에 부모의 this을 쓰기 위해 relationship1처럼 변수를 새로 선언하여 부모의 this을 끌어와야한다.