본문 바로가기

목차 🡻


JavaScript/VanillaJS

ES6 화살표함수

by ​​​​ 2020. 8. 9.

1.화살표함수는 함수이름이 없는 익명함수

(x, y) => x + y; // 선언됐지만 이름이 없어 사용할법이 없다


const add = (x, y) => x + y; // 이렇게 익명함수는 변수에 할당할수있다
console.log(add(1, 3)); // 4


setTimeout(() => {
  console.log('arrow function'); // 또는 이렇게 함수를 인자로 넣어줘야할때 주로 화살표 함수를 사용한다
}, 0);

익명함수는 이런식으로 사용할수있습니다.

그리고 같은 함수라도 여러가지 방법으로 쓸수있는데

let mul1 = (a, b) => {
  return a * b;
};

let mul2 = (a, b) => (a * b);

let mul3 = (a, b) => a * b;

console.log(mul1(2, 3)); // 6
console.log(mul2(2, 3)); // 6
console.log(mul3(2, 3)); // 6

이렇게 모두 다르게 선언했지만 같은 동작을 수행하는 함수들입니다.

보통은 화살표함수는 식이 간단할때만 쓰기 때문에 거의 mul3같은식으로 사용합니다

 

2. 화살표함수는 상위 스코프의 this를 물려받는다

화살표함수는 일반 함수와는 다른게 this가 가리키는 대상인데요

const lang = {
  name: "js",
  f: function () {
    console.log("f함수 호출==============");
    console.log("this.name: ", this.name); // js 출력
    console.log("this는 lang인가:  ", this === lang); // true 출력
    console.log("this는 글로벌객체:  ", this === global); // false 출력
    function normal() {
      console.log("일반함수 호출==============");
      console.log("this.name: ", this.name); // undefined 출력
      console.log("this는 lang인가:  ", this === lang); // false 출력
      console.log("this는 글로벌객체:  ", this === global); // true 출력
    }
    normal();

    const arrow = () => {
      console.log("화살표함수 호출==============");
      console.log("this.name: ", this.name); // js 출력
      console.log("this는 lang인가:  ", this === lang); // true 출력
      console.log("this는 글로벌객체:  ", this === global); // false 출력
    };
    arrow();
  },
};
lang.f();

이렇게 일반함수는 상위스코프인 f의 this와 별개인 this를 가지는 반면에

화살표함수는 상위 스코프인 f의 this를 그대로 내려받습니다. 

'JavaScript > VanillaJS' 카테고리의 다른 글

module.exports JS  (0) 2020.08.27
ES6 const,let 비구조화할당 템플릿문자열  (0) 2020.08.08
자바스크립트 Closure 클로저란  (0) 2020.04.04