기존 function과 다른 점은 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();
    
    const relationship2 = {
      name: 'zero',
      friends: ['nero', 'hero', 'xero'],
      logFriends() {
        this.friends.forEach(friend => {
          console.log(this.name, friend);
        });
      },
    };
    relationship2.logFriends();

    relationship1.logFriends() 안의 forEach문에서는 function 선언문을 사용했습니다. 각자 다른 함수 스코프의 this를 가지므로 that이라는 변수를 사용해서 relationship1에 간접적으로 접근하고 있습니다.

    하지만 relationship2.logFriends() 안의 forEach문에서는 화살표 함수를 사용했습니다. 따라서 바깥 스코프인 logFriends()this를 그대로 사용할 수 있습니다. 상위 스코프의 this를 그대로 물려받는 것입니다.

    즉, 기본적으로 화살표 함수를 쓰되, this를 사용해야 하는 경우에는 화살표 함수와 함수 선언문(function) 둘 중 하나를 고르면 됩니다.

    신간 소식 구독하기
    뉴스레터에 가입하시고 이메일로 신간 소식을 받아 보세요.