Page 25 -
P. 25

기존 function과 다른 점은 this 바인드 방식입니다. 다음 예제를 봅시다.

                      var relationship1 = {
                        name: 'zero',
                        friends: ['nero', 'hero', 'xero'],                                            2
                        logFriends: function () {
                          var that = this; // relationship1을 가리키는 this를 that에 저장
                          this.friends.forEach(function (friend) {
                            console.log(that.name, friend);                                           알아두어야 할 자바스크립트
                          });
                        },
                      };
                      relationship1.logFriends();


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


                    relationship1.logFriends() 안의 forEach문에서는 function 선언문을 사용했습니다. 각자 다른
                    함수 스코프의 this를 가지므로 that이라는 변수를 사용해서 relationship1에 간접적으로 접근하
                    고 있습니다.

                    하지만 relationship2.logFriends() 안의 forEach문에서는 화살표 함수를 사용했습니다. 따라서
                    바깥 스코프인 logFriends()의 this를 그대로 사용할 수 있습니다. 상위 스코프의 this를 그대로
                    물려받는 것입니다.

                    즉, 기본적으로 화살표 함수를 쓰되, this를 사용해야 하는 경우에는 화살표 함수와 함수 선언문
                    (function) 중에서 하나를 고르면 됩니다.





                    2.1.5 구조분해 할당


                    구조분해 할당을 사용하면 객체와 배열로부터 속성이나 요소를 쉽게 꺼낼 수 있습니다.


                                                                                                  71





     node_06.indd   71                                                                      2020-07-14   오전 11:02:01
   20   21   22   23   24   25   26   27   28   29   30