프론트엔드/Javascript, TS

[Javascript] 일반함수와 화살표함수의 차이점 (this의 쓰임, new 키워드, arguments 바인딩, 파라미터 중복 불가, 중괄호)

데브힐러 2022. 1. 17. 21:42
반응형

1. Syntax

let add = (x, y) => x + y;
  • 위와같이 오른쪽의 표현식이 하나라면 중괄호를 필요로 하지 않는다.
let squareNum = x => x \* x;
  • 위와 같이 argument가 한개라면 소괄호()를 생략해도 된다.

2. Arguments Binding

  • (argument는 함수 안에서 접근 가능한 Object로써 함수에 전달되는 argument의 값을 포함한다.)
  • arrow함수는 arguments 바인딩을 가지지 않는다. 그러나 가장 가까운 non-arrow형태의 부모함수에의
    arguments 오브젝트에는 접근 가능하다.

3. 'this' keyword 사용 가능 유무

  • 일반함수와 다르게 arrow함수는 자기자신의 this가 없다. arrow함수 내부의 this의 value는 함수의 lifecycle에 걸쳐 동일하게 유지된다. 그리고 가장 가까운 non-arrow형태인 부모함수의 this값에 바인딩 되어있다.

let me = {
  name: "Dev Healer",
  thisInArrow: () => {
    console.log("My name is " + this.name); // 'this'는 undefined 이다.
  },
  thisInRegular() {
    console.log("My name is " + this.name); // 'this' binding 이 작용한다.
  },
};
me.thisInArrow();
me.thisInRegular();

4. 'new' keyword 차이

  • 표현식이나 함수선언으로 만들어진 일반함수는 생성자 호출과 호출이 가능하다.
  • 생성자 호출이 가능하므로 new키워드를 통해 호출될 수 있다.
  • 그러나 arrow함수는 호출될 수는 있으나 생성자 호출은 할 수 없다. 예를 들어
    arrow함수는 생성자로 쓰이지 않는다. 따라서 new키워드와 함께 불릴 수 없다.

let add = (x, y) => console.log(x + y);
new add(2,3);

// 결과 : 에러 add is not a constructor 

5. No duplicate named parameters

  • arrow함수는 strict모드에서건 non-strict모드에서건 duplicated named파라미터를 쓸 수 없다.
  • 일반 함수는 non-strict모드에서만 duplicated named 파라미터를 쓸 수 있다.

function add(x, x){}

// Ok

'use strict';  
function add(x, x){}  
// SyntaxError: duplicate formal argument x

(x, x) => {}  
// SyntaxError: duplicate argument names not allowed in this context

참조

반응형