본문 바로가기
javascript

[Javascript] 화살표 함수 Arrow Function

by dyyoo 2019. 11. 21.

function 선언 대신 => 기호로 함수를 선언할 수 있다.

 

변수에 대입하면 나중에 재사용 가능하다.

 

기존의 function과 다른점은 this 바인드 방식.

 

아래 코드를 보면,

1. relationship1의 forEach 안의 function에선, 각자 다른 스코프의 this를 가지므로, that에 this를 대입해서 사용

2. relationship2의 forEach는 화살표 함수를 사용했음. logFriends()의 this를 그대로 사용 가능.

 

const relationship1 = {
    name: 'zero',
    friends: [],
    logFriends: function() {
        let that = this; //relationship1을 가리키는 this를 that에 저장
        this.friends.forEach(function(friend) {
            console.log(that.name, friend);
        });
    }
}
relationship1.logFriends();

const relationship2 = {
    name: 'zero',
    friends: [],
    logFriends() {
        this.friends.forEach(friend => {
            console.log(that.name, friend);
        });
    }
}

 

this도 따로 정리해야겠다.

댓글