JS - this 에 대한 문제

Jaa-van·2023년 4월 6일
0
post-thumbnail
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());
console.log('It is', fighter.getName(), 'VS', fighter.getFirstName(), fighter.getLastName);

1. fighter.opponent.getFullname()

는 opponent라는 객체의 method getFullname 에서 호출된 this 를 가지고 있으므로 this 는 opponent가 된다. 따라서 opponent.fullname 은 'Francis Ngannou'

2. fighter.getName()

는 getName() 은 fighter 객체의 내부함수 이지만 fighter.getName() 은 메서드 로서 호출된 것이기 때문에 this 는 fighter 가 된다. 따라서 'John Jones'

3. fighter.getFistName()

는 화살표 함수로 이루어져 있어 this binding 이 이뤄지지 않기 때문에 전역객체를 바라보게 되는 것이고 전역객체.fullname = 'Ciryl' 이 된다

4. fighter.getLastName

는 getLastName 안에 즉시 실행 함수가 들어있고 선언의 주체가 없기 때문에 this binding 이 이뤄지지 않아 this 는 전역객체를 바라보게 된다. 따라서 'Gane' 가 된다

1개의 댓글

comment-user-thumbnail
2023년 4월 8일

깔끔하고 이쁘게 잘 정리된 글! 잘 보고갑니다!

답글 달기

관련 채용 정보