[Node.js] 화살표 함수

Cjw.dev·2023년 2월 21일

Node.js

목록 보기
2/10
// 아래 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();
  • 화살표 함수가 기존 function(){}를 대체하는건 아니다(this가 달라짐)
  • function은 자신만의 this를 갖는다. 부모의 this를 가져오려면 this를 that과 같은 변수에 담에서 가져와야 한다.
  • logFriends의 메서드 값에 주목
  • forEach의 function의 this와 logFriends의 this는 다름
  • that 이라는 중간 변수를 이용해서 logFriends의 this를 전달
// () => {} 에서의 this
const result2 = {
    name : "원재",
    friends : ["수지", "철수", "영희"],
    logFriends : function(){
        const that = this; 
        this.friends.forEach((friend)=>{
            console.log(this.name, friend); 
        })
    },
}
result2.logFriends();
  • forEach의 인자로 화살표 함수가 들어간 것에 주목
  • forEach의 화살표함수의 this와 logFriends의 this가 같아짐
  • 물려받고 싶지 않을 때 : function(){}을 사용하면 된다.

또 다른 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); //
});
profile
백엔드 개발 공부 기록 22.11.07 ~ ing

0개의 댓글