Node.JS

[Node.js 교과서]1-5. 화살표 함수

옴악핫세 2023. 12. 15. 18:37

함수를 선언할 때, 화살표 함수를 이용하면 조금 더 간결하게 함수를 선언할 수 있음

 

add1~4는 다 같은 함수

 

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);

//주의 사항! 화살표 함수 return이 객체면 소괄호로 감싸서 return 선언해야함
const obj = (x,y) => ({x,y})

 

 

아래 not1, not2도 같은 함수

function not1(x) {
    return !x;
}

const not2 = x => !x;

 

 

 

arrow Function과 Function에서의 This

//일반 함수에서의 this
this;
button.addEventListener('click', function (){
    console.log(this.textContent);
    //출력되는 this는 함수 내부의 this
})


//arrow function에서의 this
this; 
button.addEventListener('click', (e)=> {
    console.log(this.textContent);
    //출력되는 this는 바깥의 10번째 줄의 this
    // console.log(e.target.textContent); 와 같음
})

 

this를 쓰려면 function으로 함수를 선언

this를 안쓰면 arrow function을 쓰는 것이 좋음!