Lamda 표현식

  1. function 표현식과 Lamda 표현식을 사용할 때 주의해야할 부분

예제)

var relationship1 = {
    name: 'zero',
    friend: ['nero','hero','xero'],
    logFriends: function() {
        var that = this;
        this.friend.forEach(function(friend){
            console.log(that.name, friend);
        })
    }
}
var relationship1 = {
    name: 'zero',
    friend: ['nero','hero','xero'],
    logFriends: function() {
        var that = this;
        this.friend.forEach((friend) => {
            console.log(this.name, friend)
        })
    }
}

첫번째 코드는 function 표현식을 쓴 코드이고, 두번째는 람다 표현식을 쓴 코드이다. 차이점은 함수의 내부에서 this 가 가리키는 객체인데, 첫번째는 function 함수 내부를 가리키기 때문에 relationship1 객체에 접근할 수 가 없어 that이라는 객체를 사전에 선언하여 접근하는 방식을 보이고 있고,
두번째 lamda식에서는 내부에서 this가 logFriends 함수 외부를 가리키고 있기 때문에 직접 relationship1.name에 접근하는게 가능하다.