JavaScript: Arrow Function, When to avoid it

Jene Hojin Choi·2021년 2월 10일
0

JavaScript

목록 보기
5/15
post-thumbnail

1. Defining a function (ES5)

1-1. function declaration

1-2. function expression

anonymous function 을 사용하여 function을 declare 하는 경우는 다음과 같다:

2. arrow function notation (ES6)

하지만 ES6 버전에서 자바스크립트는 새롭게 함수를 작성하는 법을 내놓았다. 이것이 바로 arrow function이다.

arrow function의 기본적인 문법은 다음과 같다. function keyword를 생략할 수 았고, =>를 써서 코드를 더 간결하게 표현할 수 있는 것이 특징이다.

3. concise body arrow function

concise body 는 Javascript의 arrow function을 더 간결하게 해줄 수 있는 방법이다.

3-1. parameter and parentheses

하나의 인자만을 받는 function의 경우에는 ()괄호가 필요가 없다. 그러나, 0개 혹은 여러개의 인자를 받는 경우에는 괄호가 필요하다.

3-2.single-line vs multi-line

함수의 body가 한줄로 이루어진 경우에는 중괄호가 필요가 없고, return도 생략해줄 수 있다. 하지만 여러줄로 이루어진 경우에는 중괄호를 넣어주어야하고, return도 써주어야한다.

const plantNeedsWater = (day) => {
  return day === 'Wednesday' ? true : false;
};

위의 코드를 concise body를 사용하면 아래와 같이 줄일 수 있다.

const plantNeedsWater = day => day === 'Wednesday' ? true : false;

4. Avoid arrow function : 'this'

위를 통해 arrow function을 사용하면 매우 간편하다는 것을 알 수 있다. 하지만 이것이 모든 곳에서 만능으로 쓰이는 것은 아니다.

특히, this 키워드를 사용하는 경우에는 문제가 생길 수 있다.

자바스크립트 공식 문서에 다음과 같은 말이 있다:

As stated previously, arrow function expressions are best suited for non-method functions.

arrow function을 쓰는 것이 method로 쓰이지 않을 때에 가장 적합하다는 말이다.

왜 이런 것일까?
그렇다면 적합하지 않은 경우, 즉 arrow functionmethod로 쓰는 경우를 살펴보자.

object 안에서 checkEnergy()라는 method를 선언하려고 한다.
아래의 코드와 같이 일반적인 function declaration을 쓴다면 큰 문제 없이 기대한 결과값을 얻을 수 있다.

const robot = {
  energyLevel: 100,
  checkEnergy(){
    console.log(`Energy is currently at ${this.energyLevel}%.`)
  }
}

robot.checkEnergy();
>> Energy is currently at 100%.

하지만, 아래와 같이 arrow function을 이용해 method를 선언하려고 한다면 오작동을 하는 것을 볼 수 있다. 100%가 나와야할 부분에 undefined 가 나온다!

const robot = {
  energyLevel: 100,
  checkEnergy: () => {
    console.log(`Energy is currently at ${this.energyLevel}%.`)
  }
}

robot.checkEnergy();
>> Energy is currently at undefined%.

arrow function을 이용해 함수를 선언할 때에는 this에 binding할 객체가 정적으로 결정된다.
arrow functionthis에 대한 binding이 없다.
그러므로 arrow functionthis는 상위 객체의 scope에서 this이다. 이를 lexical this라고 말한다.

그러므로 위와 같이 methodarrow function으로 작성한다면, this라는 객체는 상위 환경의 this를 계승하게 된다. 그러므로 이는 global object (전역 객체)를 가리키게 된다.

그러므로 이 thisenergyLevel이라는 property를 갖고 있지 않기 때문에 undefined를 리턴하는 것이다.

Limitations of arrow function

위와 같은 식으로 arrow function을 피해야하는 경우들이 여러가지가 있는데, 이는 자바스크립트 공식 문서에 다음과 같이 설명이 되어있다.

Differences & Limitations:

  • Does not have its own bindings to this or super, and should not be used as methods.
  • Does not have arguments, or new.target keywords.
  • Not suitable for call, apply and bind methods, which generally rely on establishing a scope.
  • Can not be used as constructors.
  • Can not use yield, within its body.

Wrap up

그렇다면arrow function은 언제 사용하는 것이 좋을까?
this가 필요 없는 일반 함수에 사용하는 것이 좋다.

0개의 댓글