화살표 함수
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;
객체를 리턴하는 경우에는 소괄호는 필수이다.
const obj = (x, y) => ({x, y})
ex 1)
var relationship1 = {
name: 'zero',
friends: ['nero', 'hero', 'xero'],
logFriends: function() {
var that = this;
this.friends.forEach(function (friend) {
console.log(that.name, friend);
});
},
};
relationship1.logFriends();
화살표 함수가 기존 function() {}을 대체하는 건 아니다.(this가 달라짐)
var relationship2 = {
name: 'zero',
friends: ['nero', 'hero', 'xero'],
logFriends() {
this.friends.forEach(friend => {
console.log(this.name, friend);
});
},
};
relationship2.logFriends();
forEach의 인자로 화살표 함수가 들어간 것에 주목
ex 2) tag에 event 달아줄 때
button.addeventListener('click', function() {
console.log(this.textContent);// 자신의 this
});
=> 버튼을 클릭하면 단어가 출력
하지만,
button.addeventListener('click', () => {
console.log(this.textContent);// 부모의 this라서(자신의 this x)
});
=> 동작 안함
화살표 함수를 쓰려면,
button.addeventListener('click', (e) =>{
console.log(e.target.textContent);
});