[JS] 화살표 함수(Arrow Function)

post-thumbnail

화살표 함수

화살표 함수는 ES6에서 추가된 간결한 표현으로 함수를 정의할 수 있는 방법입니다.

function fun() { // 일반함수
  ...
}

const arrFun = () => { // 화살표 함수
  ...
};

일반 함수와의 차이

this

일반함수와 화살표함수는 this가 다른 곳을 가리킨다.
화살표의 this는 상위 스코프의 this와 같다.
기존의 일반 함수는 this가 동적으로 바인딩된다.

this.name = "화살표 함수";
let func = {
  name: "일반 함수",
  ArrowFunc: () => {
    console.log("Arrow Function : " + this.name);
  },
  RegularFunc() {
    console.log("Regular Function : " + this.name);
  },
};

func.ArrowFunc();
func.RegularFunc();
/* result
Arrow Function : 화살표 함수
Regular Function : 일반 함수 */

생성자 함수

일반 함수는 생성자 함수로 사용할 수 있는데 반해, 화살표 함수는 사용할 수 없습니다.
prototype 프로퍼티를 가지고 있지 않기 때문입니다.

function regularFunction() {
  this.num = 1234;
}
const arrowFunction = () => {
  this.num = 1234;
};

const A = new regularFunction();
console.log(A.num); // 1234

const B = new arrowFunction(); // Error

argument

일반 함수에서는 함수가 실행 될 때 암묵적으로 arguments 변수가 전달되어 사용할 수 있다.
화살표함수에서는 arguments 변수가 전달되지 않습니다.

//일반 함수
function regularFunc() {
  console.log(arguments); // [Arguments] { '0': 1, '1': 2, '2': 3 }
}

regularFunc(1, 2, 3);

//화살표 함수
const arrFun = () => {
  console.log(arguments); // Uncaught ReferenceError: arguments is not defined
};

arrFun(1, 2, 3);

0개의 댓글