화살표 함수

miniminion·2022년 12월 13일
0

프론트엔드

목록 보기
4/10
post-thumbnail

화살표 함수란?

화살표함수는 ES6에서 새로 추가된 내용으로서, 기존 함수 표현식과 비교하여 보다 간결하게 사용할 수 있다는 장점이 있다.

(ES란, ECMAScript의 약자이며 자바스크립트의 표준, 규격을 나타내는 용어이다. 뒤에 숫자는 버전을 뜻하고 ES5는 2009년 ES6는 2015년에 출시되었다.)

본래는 다음과 같이 작성하여야 하는 함수를

let sum = function (a, b) {
    return a + b;
    };

화살표함수를 사용하면 아래와 같이 쓸 수 있다.

let sum = (a, b) => a + b; 

하지만 화살표함수가 모든 면에서 기존함수와 동등하게 사용될 수 있는 것은 아니다.

1) this를 가르키는 방식의 차이
화살표 함수의 경우 this가 가리키는 객체가 정적으로 정해지기 때문에 상위 scope의 객체를 가르킨다. 일반 함수의 경우 동적으로 객체가 정해지기 때문에 자신이 현재 종속된 곳에서의 객체를 가르킨다.

function test1() {
  this.name = "짱구";
  return {
    name: "흰둥이",
    speak: function () {
      console.log(this.name);
    },
  };
}
var new_test1 = new test1();
new_test1.speak(); //흰둥이

function test2() {
  this.name = "짱구";
  return {
    name: "흰둥이",
    speak: () => console.log(this.name),
  };
}

var new_test2 = new test2();
new_test2.speak(); //짱구

2) 생성자 함수에는 사용 불가

let test1 = function () {
  this.num = 1234;
};
const test3 = new test1();
console.log(test3); //test1 { num: 1234 }


const test2 = () => (this.num = 1234);
const test4 = new test2();
console.log(test2); //TypeError: test2 is not a constructor

3) Argument 사용 불가

function print_xy() {
  console.log(arguments[0] * 2);
}
print_xy(10, 20); //20

let print_xy2 = () => console.log(arguments[0] * 2);
print_xy2(10, 20); //NaN

0개의 댓글