화살표 함수는 뭐가 다른가?

frenchkebab·2021년 10월 7일
0

javascript 지식

목록 보기
36/36
post-thumbnail

Zerocho 님의 ES2015(ES6) Function(함수) 글을 보고 작성한 글입니다.

화살표 함수


function과 다른 점


1. this가 유지된다

this에 대하여...글을 참조하자

var object = {
  name: 'Zero',
  friends: ['One', 'Two', 'Three'],
  alertFriends: function() {
    var self = this;  // 원래는 이렇게 this를 저장해 주었어야 함!
    this.friends.forEach(function(friend) {
      alert(self.name + ' and ' + friend);
    });
  }
};
object.alertFriends(); // 세 번 알림

forEach함수 안에서의 thiswindow 객체를 가리키게 된다.


그러면, 화살표 함수를 살펴보자.

const object2 = {
  name: 'Zero',
  friends: ['One', 'Two', 'Three'],
  alertFriends() {     
    this.friends.forEach((friend) => {	
      alert(this.name + ' and ' + friend);  // this가 object2로 유지된다.
    });
  }
};
object2.alertFriends();

function(매개변수) {}을 그냥 (매개변수) => {}로 바꾸었을 뿐인데 this가 그대로 유지된다.
마치 foreach((function() {}).bind(this))를 한 것과 같다.

즉, 바뀐 this가 필요할 때에만 function() {}을 사용화면 되겠다.!

하지만! 화살표 함수function을 완벽하게 대체하는 것은 아니다!
화살표 함수로 할 수 없는 2가지가 있다!
1. new 붙이기 (생성자로 사용하기)
2. arguments 사용하기


※ 참고로, 함수가 별다른 처리 없이 return을 하는 경우 간단하게 사용할 수 있다.

var long = function(x) {
  return x + 1
};

const short = (x) => x + 1;

2. default(기본 값)

var func = function(msg) {
  console.log(msg);
};

func(); // undefined
}

당연히 msg인자를 전달하지 않았기 때문에 undefined가 나온다.

하지만, 화살표 함수 (ES2015)에서는 인자를 전달하지 않았을 경우에 대비한 기본 값을 넣어줄 수 있다.

const func2 = (msg = 'hello') => {
  console.log(msg);
};

func2(); // 'hello'

defaultundefined일 경우에만 적용되며, null 일 경우에는 그냥 null 값이 들어가게 된다.


3. rest(나머지 인자들 처리)

var func3 = function(x) {
  var args = Array.prototype.slice.call(arguments, 1);
  console.log(args.length);
};

func3(1, 2, 3, 4); // [2, 3, 4]

arguments 에 대해서는 다음 글을 참조하자. arguments 객체

함수의 인자몇 개가 들어올 지 모를 때 Array.prototype.slice.call()로 나머지 인자들을 처리할 수 있다.

이것을 ES2015 문법을 사용하면 다음처럼 사용이 가능하다.

const func4 = (x, ...y) => {
  console.log(y);
};

func4(1, 2, 3, 4); // [2, 3, 4]

단, ...y 기능이 있으므로 기존의 arguments는 사용할 수 없다.
또한 이름이 rest 이므로, ...y는 항상 마지막에 와야 한다.
즉 다음과 같이 사용할 수 없다 ; const func4 = (x, ...y, z) => {}


4. spread

배열의 요소들함수의 인자 순서대로 넣으려면 다음과 같이 일일이 넣어주어야 해서 살짝 불편하다.

var array = [1, 2, 3];
var func5 = function(x, y, z) {
  alert(x + y + z);
};

func5(array[0], array[1], array[2]); // 6

다음과 같은 방법으로도 가능은 하다

func5.apply(null, array);

apply에 대해서는 다음 글을 참조하자.
-> 함수 메서드 삼총사 bind, call, apply 그리고 arguments

하지만 ES2015에서는 조금 더 직관적이게 표현할 수 있게 바뀌었다.

func5(...array);
profile
Blockchain Dev Journey

0개의 댓글