// 아래 add1, add2, add3, add4는 모두 같은 함수
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);
// 주의, add5, add6은 같은 함수
const add5 = (x,y) => {
return {x:x, y:y} // 키,밸류가 같으면 생략 가능 -> {x ,y}
}
const add6 = (x,y) => ({x ,y}); // 함수의 {}인지, object의 {}인지 엔진이 헷깔리기 때문에 ()를 넣어준다.
// 파라미터 1개의 경우
const add7 = x => (x+1); // 파라미터가1개인 경우 () 생략 가능
화살표 함수의 등장 후 코드 작성이 매우 심플해졌다.
그럼에도 function 함수는 살아지지 않았는데 그 이유를 알아보자
// function 함수에서의 this
const result = {
name : "원재",
friends : ["수지", "철수", "영희"],
logFriends : function(){
const that = this; // result를 가리키는 this를 that에 저장
this.friends.forEach(function(friend){
console.log(that.name, friend);
})
},
}
result.logFriends();
// () => {} 에서의 this
const result2 = {
name : "원재",
friends : ["수지", "철수", "영희"],
logFriends : function(){
const that = this;
this.friends.forEach((friend)=>{
console.log(this.name, friend);
})
},
}
result2.logFriends();
또 다른 function함수와 화살표 함수의 차이를 알아보자
const btn = document.querySelector("button");
btn.addEventListener("click", function() {
console.log(this.textContent); // button의 textContent가 출력
});
this;
btn.addEventListener("click", ()=> {
console.log(this.textContent); // 동작하지 않음. 밖의 this를 가르킴
});
// 화살표 함수로 사용할 경우 this사용 불가하기에 아래와 같이 사용해야 함
btn.addEventListener("click", (e)=> {
console.log(e.target.textContent); //
});