본문 바로가기

WEB/HTML CSS JS

[JS] 화살표함수

목차

Arrow Function 형태

 

let func = (arg1, arg2, ..., argN) => expression

 

  • 인수가 하나라면 괄호 생략 가능
  • 인수가 없을 땐 괄호 생략 불가능
  • 본문이 여러줄인 경우 중괄호로 묶으면 된다. 이 경우 return 문을 명시적으로 사용해줘야함.
  • 👇 이렇게도 쓸 수 있음. 처음엔 낯선데 익숙해져야함
let welcome = (age < 18) ?
  () => alert("안녕"),
  () => alert("안녕하세요");
  • 화살표 함수는 익명 함수로만 사용할 수 있다. 따라서 화살표 함수를 호출하기 위해서는 함수 표현식을 사용한다.
  • 화살표 함수는 자체 컨텍스트가 없는 짧은 코드를 담는 목적으로 만들어졌다. 아래에서 화살표 함수의 특징을 통해 이를 확인할 수 있다.

 

화살표 함수 특징

1. 화살표 함수에는 ‘this’가 없다.

  • 화살표 함수 내에서 ‘this’를 참조하면, 함수 바깥에서 값을 가져온다.
  • 화살표 함수를 사용한 아래 예시에선 this.title == group.title 이다.
 let group = {
   title: "1모둠",
   students: ["보라", "호진", "지민"],
 
   showList() {
     this.students.forEach((student) => alert(this.title + ": " + student));
     //1모둠: 보라
     //1모둠: 호진
     //1모둠: 지민
  },
};

group.showList();
  • 아래와 같이 일반 함수를 사용한다면, this.title == undefined.title 이 되어 오류가 발생한다.
  • 왜 undefined 냐면, 콜백함수를 호출하는 경우, 제어권을 가진 함수가 뭐냐에 따라 this가 달라지기 때문이다.
  • (forEach 함수는 엄격모드에선 this === undefined 이고, 엄격모드가 아닐 땐 this === 전역객체 이다.)
let group = {
  title: "1모둠",
  students: ["보라", "호진", "지민"],

  showList() {
    this.students.forEach(function(student) {
      // TypeError: Cannot read property 'title' of undefined
      alert(this.title + ': ' + student)
    });
  }
};

group.showList();
  • 하지만 화살표함수엔 this 가 없으므로 이런 오류가 발생할 일이 없다!

화살표함수에서의 this 예시 하나 더

더보기
 //화살표 함수
 function WhiteDog() {
   this.name = "흰둥이";
   return {
     name: "검둥이",
     bark: () => {
       console.log(this.name + ": 멍멍!");
     },
   };
}

const whiteDog = new WhiteDog();
whiteDog.bark(); //흰둥이: 멍멍!
//일반 함수
function BlackDog() {
  this.name = "흰둥이";
  return {
    name: "검둥이",
    bark: function() {
      console.log(this.name + ": 멍멍!");
    },
  };
}

const blackdog = new BlackDog();
blackdog.bark(); //검둥이: 멍멍!

 

1.1 ‘this’가 없기 때문에 생성자 함수로 사용할 수 없다

var Foo = () => {};
var foo = new Foo(); // TypeError: Foo is not a constructor
  • 따라서 new와 함께 호출할 수 없다.
  • 따라서 prototype 도 없다.

 

2. 화살표함수엔 'arguments' 가 없다.

  • 화살표 함수에서 arguments 객체에 접근하면, 화살표 함수 바깥의 외부함수에서 arguments 를 가져온다.
  • arguments 가 바인딩 되지 않으므로, 그냥 외부 스코프에서 arguments 키워드를 찾는 셈이다.
  • 대신 나머지 연산자(rest parameters)가 좋은 대안이 될 수 있다.
  • 나머지 연산자가 arguments 보다 더 최신 문법이고, 배열 메서드를 사용할 수 있는 등 더 편리하니까 이것도 화살표함수의 장점.
function foo(n) {
  var f = (...args) => args[0] + n;
  return f(2);
}

foo(1); // 3

 

3. 화살표함수는 호이스팅 되지 않는다.

  • 따라서 코드 실행흐름이 함수 선언에 도달하지 않은 상태에선, 함수를 호출할 수 없다.

 

this나 호이스팅처럼 자바스크립트 코드를 읽을 때 머리 아프게 하는 것들을 생각하지 않아도 된다는 점에서

화살표 함수는 더 편하다 !


 

화살표 함수를 사용하면 안되는 케이스

1. Object 의 method 로 화살표 함수를 사용하면 안된다.

화살표함수엔 this 가 없기 때문에 parent scope 에서 this 를 가져온다.

따라서 아래 예시에서 this는 cat이 아닌, 전역객체를 가리키게 되고, lives 값이 감소하지 않는다.

X

var cat = {
  lives: 9,
  jumps: () => {
    this.lives--;
  }
}

cat.jumps();
cat.jumps();
console.log(cat.lives);		// 9

O

var cat = {
  lives: 9,
  jumps: function() {
    this.lives--;
  }
}

cat.jumps();
cat.jumps();
console.log(cat.lives);		// 7

 

참고

 

 

화살표함수 | 재미있는 기억만 남기자

화살표함수 🔗 🔗 🔗 저는 gitlab FE 인터뷰 자료의 javascript 를 다 읽어보고 공부를 하고 있습니다. 몇몇 스터디 원분들께서는 그래서 제가 정리한 공부의 문맥이 이해가 안되실 수 있습니다. 문

eyabc.github.io

 

화살표 함수 - JavaScript | MDN

화살표 함수 표현(arrow function expression)은 function 표현에 비해 구문이 짧고  자신의 this, arguments, super 또는 new.target을 바인딩 하지 않습니다. 화살표 함수는 항상 익명입니다. 이  함수 표현은 메

developer.mozilla.org

더 읽어보기

아래 두 링크에서는 화살표함수를 쓰면 안되는 케이스에 대해 소개한다. 어려워서 나중에 읽어야지.

 

JavaScript Arrow Functions: How, Why, When (and WHEN NOT) to Use Them

One of the most heralded features in modern JavaScript is the introduction of arrow functions, sometimes called 'fat arrow' functions, utilizing the new token =>.

zendev.com

 

 

When (and why) you should use ES6 arrow functions — and when you shouldn’t

by Cynthia Lee When (and why) you should use ES6 arrow functions — and when you shouldn’tArrow functions (also called “fat arrow functions”) are undoubtedly one of the more popular features of ES6. They introduced a new way of writing concise funct

www.freecodecamp.org

더 어려워보이는 글

https://hacks.mozilla.org/2015/06/es6-in-depth-arrow-functions/

https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Functions/Arrow_functions