화살표 함수
Code
function add1(x, y) {
return x + y;
};
const add2 = (x, y) => {
return x + y;
};
const add3 = (x, y) => x + y;
const add4 = (x, y) => (x + y);
function not1(x) {
return !x;
};
const not2 = x => !x;
화살표 함수를 사용하면 코드를 짧게 줄일 수 있다.
사용법
- 함수를 선언할 때 function 선언문 대신 ⇒ 기호로 함수 선언
// function
function add(x, y) {
return x + y;
}
// 화살표 함수
const add = (x, y) => {
return x + y;
}
- 함수 내부에 return문 밖에 없다면 ⇒ 기호 뒤에 return 할 식 적기
(매개변수가 1개라면 소괄호로 묶어주지 않아도 됨.)
// return
const add = (x, y) => (x + y);
const add = (x, y) => x + y;
// 매개변수 1개
const not = x => !x;
this 바인딩
Code
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);
});
},
};
relationship1.logFriends();
const relationship2 = {
name: 'zero',
friends: ['nero', 'hero', 'xero'],
logFriends() {
this.friends.forEach(friend => {
console.log(this.name, friend);
});
},
};
relationship2.logFriends();
화살표 함수를 사용하면 상위 스코프의 this를 그대로 물려받을 수 있다.