자바스크립트의 this는 자바의 this 개념과 많이 다른 것 같다.
이해는 했지만...
뇌 가비지 컬렉션에 의해서 삭제될 것 같다.

 


 

어떤 어려움이 있었는지?

아래 코드에서  log가 어떻게 출력되는지 맞추는 과제였다.

var fullname = 'Ciryl Gane'

var fighter = {
    fullname: 'John Jones',
    opponent: {
        fullname: 'Francis Ngannou',
        getFullname: function () {
            return this.fullname;
        }
    },

    getName: function() {
        return this.fullname;
    },

    getFirstName: () => {
        return this.fullname.split(' ')[0];
    },

    getLastName: (function() {
        return this.fullname.split(' ')[1];
    })()

}

console.log('Not', fighter.opponent.getFullname(), 'VS', fighter.getName()); // Not Francis Ngannou vs  John Jones
console.log('It is', fighter.getName(), 'VS', fighter.getFirstName(), fighter.getLastName); // It is John Jones vs Ciryl Gane

 

 

 나는 정답을 아래와 같이 썼다.

// Not Francis Ngannou vs John Jones
// It is John Jones vs JohnJones

 

하지만 It is John Jones vs JohnJones 이게아니라 It is John Jones vs Ciryl Gane 이거였다. 

 

배움에는 뭐가 있었지?

내가 강의를 졸면서 봤나보다. 다시 강의를 보았고 다시 기억이 났다.
함수는 this를 전역을 가리킨다는 것이다.

fighter.getLastName 는 콜백함수이다. 콜백함수도 함수이기 때문에 전역을 가리키게되고 결국은 'Ciryl Gane' 를 가리키게 된다.

console.log('It is', fighter.getName(), 'VS', fighter.getFirstName(), fighter.getLastName);
복사했습니다!