헷갈리는 화살표함수를 정리해보자 한다.

1. 왜생겼을까?
 - 함수를 좀 간결하게 쓰려고(한줄로)
 - javascript OOP 형태로 Class에 넣어서 코딩할때 this의 바인딩 문제를 해결하기 위해


2. 함수를 한줄로의 관점에서


function sum(a, b) { // 익숙한 표준 함수 : 길다 길어..
    return a+ b
}

let arrowSum = (a, b) => { // function 대신에 ()가 들어가서 좀 짧긴하지만 그래도...
    return a + b
};

let oneLineArrowSum = (a, b) => a + b; // { return expression } 을 a + b로 표현했다(간결하다)

function isPositive(number) { // 익숙한 표준 함수 2
    return number >= 0
}

let arrowIsPositive = (number) => number >= 0; // number >= 0 으로 간결하게 표현

let arrowIsPositive2 = number => number >= 0; // 파라미터가 하나 일때는 괄호를 제외할 수 있다

function randomNumber() { // 익숙한 표준 함수 3
    return Math.random()
}

let randomNumber2 = () => Math.random(); // 파라미터가 없을 경우 ()로 시작

document.addEventListener('click', function () { // 익숙한 표준 함수 4
    console.log('Click')
});

document.addEventListener('click', ()=> console.log('Click')); // 한줄로 깔끔하게!

3. this 바인딩 문제의 관점에서


class Person {
    constructor(name) {
        this.name = name
    }

    arrowPrintName() {
        setTimeout(() => {
            console.log(this);
            console.log('Arrow ' + this.name)
        }, 100)
    }

    normalPrintName() {
        setTimeout(function () {
            console.log(this);
            console.log('Function: ' + this.name)
        }, 100)
    }
}

person = new Person('이승우');
person.arrowPrintName() // Person의 this.name이 정상적으로 출력 + this는 Person을 가르킴
person.normalPrintName() // this는 엉뚱한 windows 전역변수를 가르킴(this.name은 당연히 출력 안됨)

 

4. 결론

 - 잘 만쓰면 코드도 깔끔해지고 특히 js에서 OOP로 코딩할때는 필수!

'JS' 카테고리의 다른 글

javascript es6 + Promise IE11 간단히 지원  (1) 2021.06.11
javascript 비동기 재귀 함수  (0) 2020.09.28
Promise 자바스크립트(js)  (0) 2019.10.18
loading button 쉽게 만들기(with js)  (0) 2019.10.15
JS prototype(프로토타입)  (0) 2019.09.25

+ Recent posts