프론트엔드/Javascript

화살표 함수는 언제, 왜 써야할까?

꿀표 2020. 10. 30. 19:21

Answer

1. 코드의 간결성

2. 콜백함수 this에 값을 참조시킬때  (this 값에 lexical scope를 참조시킬 때) 

3. map 사용할 때 this를 넘격주어 코드를 더 쉽게 작성할 수 있음.

 

 

들어가기전

자바스크립트에서

일반 함수는 함수를 선언할 때 this에 바인딩할 객체가 동적으로 결정된다.

즉, 함수를 호출할 때 함수가 어떻게 호출되었는지에 따라 this에 바인딩할 객체가 결정된다.

this에 대해선 아래 링크 참고

poiemaweb.com/js-this

 

반면, 화살표 함수에서는 함수를 선언할 때 this에 바인딩할 객체가 정적으로 결정된다.

일반 함수와 달리 언제나 상위 스코프의 this를 가리킨다. 이를 Lexical this라고 한다.

 

this와 Arrow function

 

this를 바인딩할 때 왜 화살표함수를 쓰는지 한가지 문제 상황을 살펴보겠다.

아래 콜백함수는 undefined를 출력하고 있다.

콜백함수(setTimeout) 내부의 this는 전역 객체 window를 가리킨다.

myVar 프로퍼티는 window가 아니라 obj의 프로퍼티이기 때문에 오류가 발생한 것이다.

let obj = {
  myVar: 'foo',
  
  myFunc: function() { 
    console.log(this.myVar)   
 
    setTimeout(function() {
      console.log(this.myVar)
    }, 1000)
  }
}
obj.myFunc() // foo ... then... undefined

 

이것을 해결하기 위한 3가지 방법을 소개하겠다.

 

1. this를 변수에 할당하는 것이다. 

let obj = {
  myVar: 'foo',
  
  myFunc: function() { 
    let self = this
    console.log(this.myVar)  
  
    setTimeout(function() {
      console.log(self.myVar)
    }, 1000)
  }
}
obj.myFunc() // foo ... then... foo

2. 두번 째 방법은 bind,call,apply를 활용하는 것이다.

let obj = {
  myVar: 'foo',
  
  myFunc: function() { 
    console.log(this.myVar)  
  
    setTimeout(function() {
      console.log(this.myVar)
    }.bind(this), 1000)
  }
}
obj.myFunc() // foo ... then... foo

3. 세번 째 방법은 아래 arrow function을 사용하는 것이다. (가장 명확한 솔루션)

let obj = {
  myVar: 'foo',
  
  myFunc: function() { 
    console.log(this.myVar)  
  
    setTimeout(() => {
      console.log(this.myVar)
    }, 1000)
  }
}
obj.myFunc() // foo ... then... foo

 

 

 

 

 

Ref

freestrokes.tistory.com/103

medium.com/tfogo/advantages-and-pitfalls-of-arrow-functions-a16f0835799e#:~:text=The%20takeaway%3A%20Function%20expressions%20are,of%20this%20in%20their%20scope.