JavaScript/JavaScript 기본

화살표 함수

검정비니 2018. 8. 6. 23:30
728x90
반응형

화살표 함수 (arrow function)




ES2015 이전에는 함수를 선언하기 위해서는 function 키워드를 통해서만 함수를 선언하고 정의할 수가 있었다. 하지만, ES2015 문법에서의 화살표 함수라는 방식을 사용하면 function 키워드를 '=>'로 대체할 수 있게 된다.


단순히 키워드 대체만 있었다면 익숙한 기존의 방식을 대체할 필요가 없었을 것이다. function 키워드 대신 화살표 함수를 사용할 경우, 기존과는 다른 방식의 this 바인딩이 가능해진다.


i.e.

var relationship1 = {

name: 'zero',

friends:  ['nero', 'hero', 'xero'],

logFriends: function() {

var that = this; //relationship1에 해당하는 this를 that에 저장

this.friends.forEach(function(friend) {

console.log(that.name, friend);

});

}

};


const relationship2 = {

name: 'zero',

friends: [nero', 'hero', 'xero'],

logFriends() {

this.friends.forEach(friend => {

console.log(this.name, friend);

});

}

}



relationship1.logFriends() 안의 forEach문에서는 function 선언문을 사용했다. 각자 다른 함수 스코프의 this를 가지므로, that이라는 변수를 사용해서 relationship1에 간접적으로 접근했다.


하지만, relationship2.logFriends() 안의 forEach문에서는 화살표 함수를 사용했기 때문에, 바깥 스코프인 logFriends()의 this를 그대로 사용할 수 있다. 상위 스코프의 this를 그대로 물려 받는 것이다.


따라서, 기본적으로 화살표 함수를 쓰되, this를 사용해야하는 경우에는 화살표 함수와 함수 선언문(function) 중 하나를 골라서 사용하면 된다.

반응형